How to use same serializer for different request?

Viewed 27

Suppose I have a VehicleSerializer

class VehicleSerializer(serializers.Serializer):
    person = PersonSerializer()
    class Meta:
       model = Vehicle
       fields = ('id', 'type', 'person')

I need to use this serializer for get as well as post api. For get request this should be same, but for post request, i need to send data like:

{
  "type": "Car",
  "person": 1 (the id of the person row)
}

How can i use same Vehicle Serializer to validate this request too? As the above serializer will take only the dict value for person key. Any help will be appreciated.

1 Answers

I think you need to set the person_id field for writing.

class VehicleSerializer(serializers.ModelSerializer):
    person = PersonSerializer(read_only = True)
    person_id = serializers.IntegerField(write_only = True)

    class Meta:
       model = Vehicle
       fields = ('id', 'type', 'person', 'person_id')
Related