我有两个序列化器
class CheckItemSerializer(serializers.ModelSerializer):
class Meta:
model = CheckItem
fields = (
'item_name',
'amount',
)
class PaymentActionSerializer(serializers.ModelSerializer):
items = CheckItemSerializer(many=True, required=False)
class Meta:
model = PaymentAction
fields = [
'booking_number',
'date',
'guest_name',
'isRefund',
'lcode',
'payment_type',
'positions',
'total',
'items',
'id'
]
def create(self, validated_data):
action = PaymentAction.objects.create(**validated_data)
action.save()
if validated_data.get('items', None) is not None:
items = validated_data.pop('items')
if items is not None:
for item in items:
item_name = item['item_name']
amount = item['amount']
new_item = CheckItem.objects.create(
item_name=item_name,
amount=amount
)
new_item.save()
action.items.add(new_item)
action.save()
return action
和json
{"lcode": 123,
"total": 1,
"isRefund": false,
"booking_number": "333",
"guest_name": "me",
"positions": "1 night",
"date": "2019-07-22 00:00",
"payment_type": "nal",
"items": [
{
"item_name": "glazka",
"amount": "100"
},
{
"item_name": "glazka2",
"amount": "150"
}
]
}
我收到错误消息
"<PaymentAction: PaymentAction object>" needs to have a value for field "id" before this many-to-many relationship can be used.
我在做什么错了?
答案 0 :(得分:1)
您也将Observable.zip(
/*first api call observable*/,
/*second api call observable etc*/,
BiFunction<
/*first api call response*/,
/*second api call response*/,
/*result of function below*/> { result_of_first_call, result_of_second_call ->
//do something with result
}).subscribe {
//update your UI, etc
}
参数传递给了items
对象,但是由于此时PaymentAction
还没有主键,因此无法添加这些项目到多对多字段。
因此,您应该首先从PaymentAction
弹出该内容:
validated_data