【发布时间】:2019-08-06 20:58:35
【问题描述】:
我有一些模型,它们相互嵌套。我想为 2 个序列化程序进行批量创建,它们都与其他模型有关系。我查看了DRF 上的文档,但无法在我的代码中实现它。
我这样发送我的 json 数据:
{
'status':true,
'products':[
{
'painting':{'amount':10},
'product':{'id':12, }
},
{
'painting':{'amount':10},
'product':{'id':12, }
}
],
'customer':{ 'name':'Adnan',
'address':{'country':'Turkey'}
},
'total':111
}
#models.py
class Address():
...
class Customer():
address = models.ForeignKey(Address, ...)
class Painting():
...
class Product():
...
class Selling():
customer = models.ForeignKey(Customer, ...)
products = models.ManyToManyField(Product, through='SellingProduct')
class SellingProduct():
selling = models.ForeignKey(Selling, ...)
product = models.ForeignKey(Product, ...)
painting = models.ForeignKey(Painting, ...)
这是我的serializers.py
class AddressSerializer():
...
class CustomerSerializer():
address = AddressSerializer()
...
class PaintingSerializer():
...
class ProductSerializer():
...
class SellingProductSerializer():
painting = PaintingSerializer()
product = ProductSerializer()
class SellingSerializer():
customer = CustomerSerializer()
products = SellingProductSerializer(many=True)
...
def create(self, validated_data):
...
如果我这样写:
class SellingSerializer():
...
def create(self, validated_data):
customer_data = validated_data.pop('customer')
products_data = validated_data.pop('products')
selling = Selling.objects.create(**validated_data) #i didn't pass customer here
for product_data in products_data:
SellingProducts.objects.create(selling=selling, **product_data)
return selling
我收到此错误:
django.db.utils.IntegrityError: (1048, "Column 'customer_id' cannot be null")
如果我这样写:
class SellingSerializer():
...
def create(self, validated_data):
selling = Selling.objects.create(**validated_data) #i didn't pass customer here
return selling
我收到此错误:
ValueError: Cannot assign "OrderedDict...
..Selling.customer must be a "Customer" instance
- 如果数据类型是 OrderedDict,我不知道如何提取或访问数据。我该怎么做呢?
我想为 Selling 和 SellingProduct、Painting 创建一条记录,我不想在每个请求中创建 Customer、Address、Product 记录,我将使用存在(在前端选择的)数据。
提前感谢大家的帮助!
【问题讨论】:
-
您能更具体地说明您遇到的问题吗?根据 DRF 文档,您应该能够解压缩 create() 中的值并直接持久化实例
-
@MatthewHegarty 我编辑了它。
标签: python django django-rest-framework