2017-01-05 57 views
1

我正在嘗試獲取特定實例的關係和關係。我需要獲取相關對象ID和關係信息。Django Rest框架通過無法獲取穿透模型自引用多對多

我的模型都基於關係從http://charlesleifer.com/blog/self-referencing-many-many-through/

1.8.3的Django Django的和REST框架3.3.3

models.py

class Person(models.Model): 
    name = models.CharField(max_length=100) 
    relationships = models.ManyToManyField('self', through='Relationship', 
              symmetrical=False, 
              related_name='related_to') 

class RelationshipType(models.Model): 
    name = models.CharField(max_length=255) 


class Relationship(models.Model): 
    from_person = models.ForeignKey(Person, related_name='from_people') 
    to_person = models.ForeignKey(Person, related_name='to_people') 
    relationship_type = models.ForeignKey(RelationshipType) 

serializers.py

class RelationshipTypeSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = models.RelationshipType 


class RelationshipSerializer(serializers.ModelSerializer): 
    relationship_type = RelationshipTypeSerializer() 
    to_person_id = serializers.ReadOnlyField(source='to_person.id') 
    to_person_name = serializers.ReadOnlyField(source='to_person.name') 

    class Meta: 
     model = models.Relationship 
     fields = (
      'id', 
      'relationship_type', 
      'to_person_id', 
      'to_person_name', 
     ) 


class PersonSerializer(serializers.ModelSerializer): 
    annotated_relationships = RelationshipSerializer(source='relationships', many=True) 

    class Meta: 
     model = models.Person 
     fields = (
      "id", 
      "name", 
      'annotated_relationships' 
     ) 

我目前收到這樣的內容:

{ 
    "id": 88, 
    "name": "Person 88", 
    "annotated_relationships": [ 
     { 
      "id": 128 
     }, 
     { 
      "id": 130 
     } 
    ] 
} 

我想是這樣的,雖然格式並不需要是這樣,只要我能得到的關係的信息:

{ 
    "id": 88, 
    "name": "Person 88", 
    "annotated_relationships": [ 
     { 
      "id": 128, 
      "relationship_type": 
       { 
        "name": "friend", 
       }, 
      "to_person_id": 34, 
      "to_person_name": "Jeremy", 

     }, 
     { 
      "id": 130, 
      "relationship_type": 
       { 
        "name": "enemy", 
       }, 
      "to_person_id": 73, 
      "to_person_name": "Trisha", 
     } 
    ] 
} 
+1

我認爲你需要定義一個方法def'get_relations(self): return models.Relationship.objects.get(from_person = self)'然後做'annotated_relationships = RelationshipSerializer(source = get_relations,many = True)' –

+0

謝謝!如果你想讓這個答案,我會接受它。 – TheCaptan

+0

謝謝!作爲回答添加回答 –

回答

1

可以定義一個方法

def get_relations(self): 
    return models.Relationship.objects.get(from_person=self) 

然後做

annotated_relationships = RelationshipSerializer(source=get_relations,many=True) 
+0

我編輯的代碼更清晰。大多數情況下,我不回頭,並感到困惑。 – TheCaptan

相關問題