在Djang中序列化递归多个模型

2024-10-02 16:27:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为我的Django应用程序编写restapi,在序列化递归多对多关系时遇到问题。我在互联网上找到了一些帮助,但是这些帮助似乎只适用于没有指定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")

我试着写这个序列化程序:

^{pr2}$

所以我必须写一些东西来序列化相关的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
            }
        ]
    }
]

但是我不知道如何编写序列化程序,所以希望您能提供一些帮助。在


Tags: name模型selfidmodel序列化time关系