2017-08-31 41 views
0

比方說,我有三個型號:DRF從外鍵的兩個方向序列化字段?

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

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

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

我們也可以說我做了頂層ViewSets和串行器的上方。十分簡單。

現在我想創建一個基於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語句來實現我要找的值是多少?

回答

0

喜歡的東西

class ThingTwoSerializer(ModelSerializer): 

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

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

我要去堵塞這和嘗試,但不會它包括ALL ThingOne的領域? – Eric

相關問題