gpt4 book ai didi

python - Django REST - 如何获取具有两个模型的 JSON?

转载 作者:太空宇宙 更新时间:2023-11-03 17:48:29 25 4
gpt4 key购买 nike

我有两个模型( map 和地点),我想使用这两个模型创建一个 JSON( map 包含多个地点)。

models.py

class Map(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=200)

class Place(models.Model):
map = models.ForeignKey('main.Map')
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=200)

我用它来单独序列化这些模型:

serializers.py

class MapSerializer(serializers.ModelSerializer):
class Meta:
model = Map
fields = ('id', 'name')

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

我想要一个像这样的 JSON,但我不知道如何正确序列化它......

{
"maplist": {
"maps": [
{
"id": "1",
"name": "dust2",
"places": [
{
"id": "1",
"name": "Long"
},
{
"id": "2",
"name": "Middle"
}
]
},
{
"id": "2",
"name": "inferno",
"places": [
{
"id": "1",
"name": "Middle"
},
{
"id": "2",
"name": "ASite"
}
]
}


]
}
}

预先感谢您的帮助。

最佳答案

尝试使用嵌套序列化器:

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

class MapSerializer(serializers.ModelSerializer):
places = PlaceSerializer(many=True)
class Meta:
model = Map
fields = ('id', 'name')

要实现此目的,您需要更改模型以包含与外键相关的名称:

class Place(models.Model):
map = models.ForeignKey('main.Map', related_name="places")
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=200)

关于python - Django REST - 如何获取具有两个模型的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29417108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com