django如何用带有m2m数据的字典创建一个对象

时间:2015-02-06 09:16:50

标签: python django dictionary

我的模特:

class Book(models.Model):
    title = models.CharField(max_length=254)
    subtitle = models.CharField(max_length=254, null=True, blank=True)
    subjects = models.ManyToManyField(Subject)

class Subject(models.Model):
    name = models.CharField(max_length=255)
    description = models.CharField(max_length=254, null=True, blank=True)

我有一个这样的字典:

dictionary = {'title':'test', 'subtitle':'test subtitle', 'subjects':[1,6]}

如何使用字典中的字段数据以编程方式创建图书模型。

def create_obj(class, dictionary):
    pass

2 个答案:

答案 0 :(得分:1)

您可以为M2M字段分配ID列表。相关管理器会将此列表转换为有效的Subject对象:

book = Book.objects.create(title=dictionary['title'],
                           subtitle=dictionary['subtitle'])
book.subjects = dictionary['subjects']

如果你想"反序列化"从这样的字典中的模型然后你可以做这样的事情:

def create_obj(klass, dictionary):
    obj = klass()

    # set regular fields
    for field, value in dictionary.iteritems():
        if not isinstance(value, list):
            setattr(obj, field, value)

    obj.save()

    # set M2M fields
    for field, value in dictionary.iteritems():
        if isinstance(value, list):
            setattr(obj, field, value)

    return obj

book = create_obj(Book, dictionary)

答案 1 :(得分:0)

book = Book()
book.title = dictionary['title']
book.subtitle = dictionary['subtitle']
book.subjects = dictionary['subjects']
book.save()