Python 在Django中序列化递归多目标模型

Python 在Django中序列化递归多目标模型,python,django,serialization,django-rest-framework,Python,Django,Serialization,Django Rest Framework,我正在为Django应用程序编写RESTAPI,在序列化递归多对多关系时遇到问题。我在互联网上找到了一些帮助,但它似乎只适用于递归多对多关系,没有指定到模型 我的模型如下: class Place(models.Model): name = models.CharField(max_length=60) other_places = models.ManyToManyField('self', through='PlaceToPlace', symmetrical=False)

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

我的模型如下:

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
            }
        ]
    }
]

但是我不知道如何编写序列化程序,因此非常感谢您的帮助。

您找到了这个问题的答案吗?