在Django中序列化递归的ManyToMany模型

时间:2014-09-20 22:31:16

标签: python django serialization django-rest-framework

我正在为我的Django应用程序编写REST API,并且在序列化递归的多对多关系时遇到了问题。我在互联网上找到了一些帮助,但它似乎只适用于没有指定through模型的递归多对多关系。

我的模型如下:

class Place(models.Model):
    name = models.CharField(max_length=60)

    other_places = models.ManyToManyField('self', through='PlaceToPlace', symmetrical=False)

    def __str__(self):
        return self.name


class PlaceToPlace(models.Model):
    travel_time = models.BigIntegerField()
    origin_place = models.ForeignKey(Place, related_name="destination_places")
    destination_place = models.ForeignKey(Place, related_name="origin_places")

我尝试编写这个序列化程序:

class PlaceToPlaceSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.Field(source='destination_places.id')
    name = serializers.Field(source='destination_places.name')

    class Meta:
        model = PlaceToPlace
        fields = ('id', 'name', 'travel_time')


class PlaceFullSerializer(serializers.ModelSerializer):
    class Meta:
        model = Place
        fields = ('id', 'name')

所以我必须写一些东西来序列化相关的Place实例,所以我得到这样的东西:

[
    {
        "id": 1, 
        "name": "Place 1",
        "places":
        [
            {
                "id": 2, 
                "name": "Place 2",
                "travel_time": 300
            }
        ]
    }, 
    {
        "id": 2, 
        "name": "Place 2",
        "places":
        [
            {
                "id": 1, 
                "name": "Place 1",
                "travel_time": 300
            }
        ]
    }
]

但我无法弄清楚如何编写序列化程序,所以非常感谢一些帮助。

0 个答案:

没有答案