django 如何使用带有 m2m 数据的字典创建对象
django how to create an object with the dictionary with m2m data
我的模特:
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
您可以将 ID 列表分配给 M2M 字段。相关管理员会将此列表转换为有效的 Subject
个对象:
book = Book.objects.create(title=dictionary['title'],
subtitle=dictionary['subtitle'])
book.subjects = dictionary['subjects']
如果您想 "deserialize" 来自此类字典的模型,那么您可以这样做:
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)
book = Book()
book.title = dictionary['title']
book.subtitle = dictionary['subtitle']
book.subjects = dictionary['subjects']
book.save()
我的模特:
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
您可以将 ID 列表分配给 M2M 字段。相关管理员会将此列表转换为有效的 Subject
个对象:
book = Book.objects.create(title=dictionary['title'],
subtitle=dictionary['subtitle'])
book.subjects = dictionary['subjects']
如果您想 "deserialize" 来自此类字典的模型,那么您可以这样做:
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)
book = Book()
book.title = dictionary['title']
book.subtitle = dictionary['subtitle']
book.subjects = dictionary['subjects']
book.save()