[Answered ]-Django Rest Framework – Nested fields: Do not create but get one from existing records

2👍

Ok here’s what I ended up doing in case it is useful to someone:

class ContactField(serializers.Field):

  def to_internal_value(self, data)
    return Contact.objects.get(pk=data.get('id'))

  def to_representation(self, obj):
    return ContactSerializer(obj).data

And

class AppointmentSerializer(serializers.ModelSerializer):

  id            = serializers.IntegerField(read_only=True)
  doctor        = ContactField()
  patient       = ContactField()

  class Meta:
    model  = Appointment
    fields = (
      'id',
      'doctor',
      'patient',
    )
👤gkpo

Leave a comment