简体   繁体   中英

Django - needs to have a value for field "id" before this many-to-many relationship can be used

I have two serializers

    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

and 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" 
    }
    ]
}

and I get error

"<PaymentAction: PaymentAction object>" needs to have a value for field "id" before this many-to-many relationship can be used.

What am I doing wrong ?

You passed the items parameter to your PaymentAction object as well, but since at that point, your PaymentAction has not (yet) a primary key, it can not add these items to a many-to-many field.

You thus should pop that from the validated_data first:

def create(self, validated_data):
    items = 
    action = PaymentAction.objects.create(**validated_data)
    if items is not None:
        items = [CheckItem.objects.create(**item) for item in items]
        action.items.add(*items)
    return action

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM