Django-必须先使用字段“ id”的值,然后才能使用这种多对多关系

时间:2019-08-14 10:01:09

标签: django django-rest-framework

我有两个序列化器

    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.

我在做什么错了?

1 个答案:

答案 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