Django REST Framework序列化程序PrimaryKeyRelatedField()未在GET响应中添​​加对象

时间:2018-10-01 17:04:11

标签: django django-rest-framework

我正在使用Django 2.x和`Django REST Framework。

我有 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
    )

serializers.py

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

    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

这很好,因为我能够更新mode_of_payment字段。但是作为响应,调用amount_given时不包含mode_of_payment对象的参数。

响应就像

{
    "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",
}

在删除行时

mode_of_payment = serializers.PrimaryKeyRelatedField(queryset=ModeOfPayment.objects.all())

确实添加了带有响应的mode_of_payment参数,但这一次不会更新mode_of_payment上的amount_given字段。

即使将mode_of_payment设置为1,为什么也不包含depth数据。

1 个答案:

答案 0 :(得分:2)

您可以创建ModeOfPaymentSerializer并在AmountGivenSerializer的to_representation()方法中使用它:

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

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

    class Meta:
        model = AmountGiven
        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

    def to_representation(self, value):
        data = super().to_representation(value)  
        mode_serializer = ModeOfPaymentSerializer(value.mode_of_payment)
        data['mode_of_payment'] = mode_serializer.data
        return data