DRF Serialize fields from both directions of foreign key?

74 views Asked by At

Let's say I have three models:

class ThingOne:
  field1 = ...
  field2 = ...

class ThingTwo:
  thingone = models.ForeignKey("ThingOne")
  field3 = ...
  field4 = ...

class ThingTree:
  thingtwo = models.ForeignKey("ThingTwo")
  field5 = ...
  field6 = ...

Let's also say I've made top level ViewSets and Serializers for the above. Easy peasy.

Now I'd like to create a custom endpoint (detail_route) that is based on a subset of ThingTwo and includes corresponding fields from ThingOne and ThingThree. I'll use a custom serializer to pack my data:

class MyComboThingSerializer(ModelSerializer):

  field1 = serializers.SerializerMethodField()
  field5 = serializers.SerializerMethodField()

  def get_field1(self, obj):
    return ?

  def get_field5(self, obj):
    return ?

  class Meta:
    model = ThingTwo
    fields = "__all__" 

What would I put into either return statement to achieve the values I'm looking for?

1

There are 1 answers

1
eugene On

Something like

class ThingTwoSerializer(ModelSerializer):

     thing1 = ThingOneSerializer()
     thingthree_set = ThingThreeSerializer(many=True)

     class Meta:
          model = ThingTwo
          fields = ['id', 'thing1', 'thingthree_set', 'field3', 'field4']