Django REST - 如何获得具有两个模型的 JSON?
Django REST - How can I get a JSON with two models?
我有两个模型(地图和地点),我想用这两个模型创建一个 JSON(地图包含多个地点)。
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)
我有两个模型(地图和地点),我想用这两个模型创建一个 JSON(地图包含多个地点)。
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)