我想创建嵌套了OrderContentSerializer的OrderSerializer,OrderContentSerializer具有PrimaryKeyRelatedField,
通过OrderContentSerializers独立保存数据时,我能够保存订单内容,但是当使用OrderSerializer时,不会创建ordercontent
我尝试直接使用列表输入(很多= true)运行OrderContentSerializer,效果很好
>>> from orders.serializers import OrderContentCreateSerializer
>>> d2=[{ "product": 1, "quantity": 1}, {"product": 1, "quantity": 1}]
>>> o=OrderContentCreateSerializer(data=d2,many=True)
>>> o.is_valid()
True
>>> o.save(order=Order.objects.get(id=1))
订单内容已创建
我知道在OrderSerializer的create方法中传递的ordercontent数据包含模型实例而不是主键的整数值
serializers.py
class OrderContentCreateSerializer(ModelSerializer):
id = serializers.IntegerField(required=False)
product = serializers.PrimaryKeyRelatedField(queryset=ProductSS.objects.all())
# service
class Meta:
model=models.OrderContent
fields = (
"id",
"product",
"quantity"
)
class OrderSerializer(ModelSerializer):
"""customer ,created by,business will be passed if the id exist in views via save methods"""
id = serializers.IntegerField(required=False)
reference = serializers.UUIDField(required=False)
created_on = serializers.DateTimeField(required=False)
completed_on = serializers.DateTimeField(required=False)
business = BusinessProfileSerializer(required=False)
ordercontent=OrderContentCreateSerializer(many=True)
class Meta:
model = models.Order
fields = (
"id",
"reference",
"total_price",
"customer_name",
"order_status",
"created_on",
"completed_on",
"paid",
"business",
"ordercontent"
)
read_only_fields = (
"id",
"reference"
)
def create(self, validated_data):
ordercontentdata = validated_data.pop("ordercontent")
# print(ordercontentdata)
order = models.Order.objects.create(**validated_data)
serializer = OrderContentCreateSerializer(data=ordercontentdata,many=True)
if serializer.is_valid():
serializer.save(order=order)
else:
order.delete()
print(serializer.errors)
return order
我不认为将需要订购模型
models.py
class OrderContent(models.Model):
order = models.ForeignKey("orders.Order",
related_name="ordercontent",
verbose_name=_("order"), on_delete=models.CASCADE)
product = models.ForeignKey("catalogs.ProductSS",
verbose_name=_("product"), on_delete=models.CASCADE,
related_name="ordercontent")
quantity = models.IntegerField(_("quantity"), default=1)
我得到的错误是
[{'product': [ErrorDetail(string='Incorrect type. Expected pk value, received ProductSS.', code='incorrect_type')]}, {'product': [ErrorDetail(string='Incorrect type. Expected pk value, received ProductSS.', code='incorrect_type')]}]
我希望能够仅通过传递外键字段的主键来使用Orderserializer直接保存订单+订单内容