gpt4 book ai didi

django - 提供给 EmbeddedDocumentField 的嵌入式文档实例无效

转载 作者:行者123 更新时间:2023-12-02 04:30:49 26 4
gpt4 key购买 nike

我目前正在开发一个计费应用程序,并且需要在账单中包含订单,因为我有以下两个模型 Bill 和 orders

 class Bill(Document):
billNo = IntField(unique=True, blank=False)
table = ReferenceField('Table',reverse_delete_rule=1)
orders = EmbeddedDocumentListField('Order', required = False)
total = models.FloatField()
discount = models.FloatField(blank=True)
grandtotal = models.FloatField()
payment_option = ReferenceField('PaymentOption',reverse_delete_rule=1)
paid = models.BooleanField(default=False)

class Order(EmbeddedDocument):
food = ReferenceField(Food)
quantity = IntField(required = True)
complementory = BooleanField(default = False)

他们的序列化器是

class OrderSerializer(EmbeddedDocumentSerializer):
class Meta:
model = Order
fields = 'all'
read_only_fields = ('id',)

class BillSerializer(DocumentSerializer):
orders = OrderSerializer(many = True)
class Meta:
model = Bill
fields = '__all__'
read_only_fields = ('id',)

def create(self, validated_data):
orders = validated_data.pop('orders')
bill = Bill.objects.create(**validated_data)
bill.orders = []

for order in orders:
print(order)
bill.orders.append(order)
bill.save()
return bill

但是每当我传递一个像

这样的 json 时
{
"billNo": "4",
"table":"5a93eb7f59951a3320a0b4d8",
"payment_option":"5a93eddf59951a2fd4dbabe9",
"orders":[{
"food":"5a93c2c759951a018c5e18b5",
"quantity":"2",
"complementory":"False"
}]
}

账单对象已创建但未添加订单并给出错误

mongoengine.errors.ValidationError: ValidationError           (Bill:5a94f76859951a19d4688aeb) 
(Invalid embedded document instance provided to an EmbeddedDocumentField: ['orders'])

我正在使用 django rest 框架,因为它是 mongodb,所以我正在使用 django rest 框架 mongo 引擎。实际错误是什么,我该怎么办?

最佳答案

改变你的OrderSerializer

class OrderSerializer(EmbeddedDocumentSerializer):
class Meta:
model = Order
fields = '__all__'
read_only_fields = ('id',)

关于django - 提供给 EmbeddedDocumentField 的嵌入式文档实例无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49002523/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com