Django Rest框架通过无法通过模型自我引用多对多

时间:2017-01-05 15:36:40

标签: python django django-rest-framework many-to-many

我正在尝试获取特定实例的关系和关系。我需要获取相关的对象id和关系信息。

我的模型基于http://charlesleifer.com/blog/self-referencing-many-many-through/

的关系

Django 1.8.3和Django Rest Framework 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 个答案:

答案 0 :(得分:1)

您可以定义方法

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

然后做

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