1

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.

  • Does this answer your question? [DRF: Simple foreign key assignment with nested serializers?](https://stackoverflow.com/questions/29950956/drf-simple-foreign-key-assignment-with-nested-serializers) – Brian Destura Jun 17 '22 at 05:36

1 Answers1

0

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')
Metalgear
  • 3,391
  • 1
  • 7
  • 16