I\'m wondering which is the best way to solve this, I have a nested serializer like this:
serializers.py:
class PaymentMethodSerializer(serializers.Model
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.