简体   繁体   English

Django REST Framework在PUT上更新外键字段

[英]Django REST Framework update foreign key field on PUT

I'm using Django 2.x and Django REST Framework 我正在使用Django 2.xDjango REST Framework

My models.py file contents 我的models.py文件内容

class ModeOfPayment(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField()

class AmountGiven(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    contact = models.ForeignKey(Contact, on_delete=models.PROTECT)
    amount = models.FloatField()
    mode_of_payment = models.ForeignKey(
        ModeOfPayment,
        on_delete=models.PROTECT,
        blank=True,
        default=None,
        null=True
    )

and serializers.py serializers.py

class ModeOfPaymentSerializer(serializers.ModelSerializer):
    class Meta:
        model = ModeOfPayment
        fields = ('id', 'title')


class AmountGivenSerializer(serializers.ModelSerializer):
    mode_of_payment = ModeOfPaymentSerializer()

    class Meta:
        model = AmountGiven
        depth = 1
        fields = (
            'id', 'contact', 'amount', 'mode_of_payment', 
        )

    def update(self, instance, validated_data):
        mode_of_payment = validated_data.pop('mode_of_payment')
        instance.mode_of_payment_id = mode_of_payment.id
        return instance

and views.py views.py

class AmountGivenViewSet(viewsets.ModelViewSet):
    serializer_class = AmountGivenSerializer
    permission_classes = (IsAuthenticated, AdminAuthenticationPermission,)
    filter_fields = ('contact__id',)

    def get_queryset(self):
        queryset = AmountGiven.objects.filter(
            contact__user=self.request.user
        )

        return queryset

But when I post data using postman with PUT method to update the existing record 但是当我使用postman通过PUT方法发布数据以更新现有记录时

在此处输入图片说明

It still says 它仍然说

{
    "mode_of_payment": [
        "This field is required."
    ]
}

Edit 2: Response after Daniel answer 编辑2:丹尼尔回答后的回应

{
    "id": "326218dc-66ab-4c01-95dc-ce85f226012d",
    "contact": {
        "id": "b1b87766-86c5-4029-aa7f-887f436d6a6e",
        "first_name": "Prince",
        "last_name": "Raj",
        "user": 3
    },
    "amount": 3000,
    "mode_of_payment": "0cd51796-a423-4b75-a0b5-80c03f7b1e65",
}

You've told AmountSerializer to accept a nested dict representing a ModeOfPayment instance, by setting the mode_of_payment field to ModeOfPaymentSerializer. 您已通过将mode_of_payment字段设置为mode_of_payment来告诉AmountSerializer接受表示ModeOfPayment实例的嵌套字典。 But that's not what you're sending; 但这不是您要发送的内容。 you're sending the ID of the ModeOfPayment. 您正在发送ModeOfPayment的ID。

You should remove that line in AmountGivenSerializer. 您应该在AmountGivenSerializer中删除该行。

Edit 编辑

I was wrong, you need to declare the field explicitly as a PrimaryKeyRelatedField: 我错了,您需要将该字段显式声明为PrimaryKeyRelatedField:

class AmountGivenSerializer(serializers.ModelSerializer):
    mode_of_payment = serializers.PrimaryKeyRelatedField(queryset=ModeOfPayment.objects.all())

    class Meta:
        ...

Now it will accept a UUID in the data. 现在它将接受数据中的UUID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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