DRF从外键的两个方向序列化字段?

时间:2017-08-31 02:09:46

标签: django django-rest-framework django-serializer

假设我有三种型号:

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

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

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

我们还说我已经为上面做了顶级的ViewSets和Serializers。十分简单。

现在我想创建一个基于ThingTwo子集的自定义端点(detail_route),并包含ThingOne和ThingThree的相应字段。我将使用自定义序列化程序来打包我的数据:

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__" 

我会在return语句中添加什么来实现我正在寻找的值?

1 个答案:

答案 0 :(得分:0)

这样的东西
class ThingTwoSerializer(ModelSerializer):

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

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