Django Rest Framework, add object to request.data and then call serializer is_valid()

前端 未结 1 1355
既然无缘
既然无缘 2021-01-27 04:34

I\'m wondering which is the best way to solve this, I have a nested serializer like this:

serializers.py:

class PaymentMethodSerializer(serializers.Model         


        
1条回答
  •  太阳男子
    2021-01-27 05:05

    Suppose payment_type is ForeignKey field in a PaymentMethod model, with null=True because of required=False.
    If you provide only a pk so you don't need serializer for it field, you can just write in fields, like all other fields.

    class PaymentMethodSerializer(serializers.ModelSerializer):
    
        data = serializers.JSONField()
    
        class Meta:
            model = PaymentMethod
            fields = ('data', 'payment_type')
    

    It will accept pk or None. If you want to provide special representation for your PaymentType model, you can override a to_representation() method.

    class PaymentMethodSerializer(serializers.ModelSerializer):
    
        ...
        def to_representation(self, instance):
            representation = super(PaymentMethodSerializer, self).to_representation(instance)
            representation['payment_type'] = PaymentTypeSerializer(instance.payment_type).data
            return representation
    

    Now it will use PaymentTypeSerializer for representation of related PaymentType model.
    You can move you payment_type validation in a serializer though. Override to_internal_value, check provided PaymentType pk and throw an exception if it wrong and then catch that exception in a view.

    0 讨论(0)
提交回复
热议问题