所以我有这个序列化器
class MovieSerializer(serializers.ModelSerializer):
class Meta:
model = Movie
fields = ('name', 'thumbnail', 'source_url', 'duration')
class SingleCategorySerializer(serializers.ModelSerializer):
movies = MovieSerializer(many=True, read_only=True)
class Meta:
model = MoviesCategories
fields = ('movies',)
电影模型与电影类别有如下关系
category = models.ForeignKey(MoviesCategories, related_name="movies", on_delete=models.DO_NOTHING)
现在当我尝试这个 serializer = SingleCategorySerializer(movie_category, many=True),serializer.data的结果为
[
{
"movies": [
{
"name": "Guardians of the Galaxy",
"thumbnail": "https://nerdist.com/wp-content/uploads/2016/08/Guardians-of-the-Galaxy-poster-2.jpg",
"source_url": "http://dl.tehmovies.org/94/10/Star.Wars/Star.Wars.Episode.II.Attack.of.the.Clones.2002.1080p.5.1CH.Tehmovies.ir.mkv",
"duration": "05:30:09"
},
{
"name": "Star Wars II",
"thumbnail": "https://images-na.ssl-images-amazon.com/images/I/51TEG6X589L.jpg",
"source_url": "http://dl.tehmovies.org/94/10/Star.Wars/Star.Wars.Episode.II.Attack.of.the.Clones.2002.1080p.5.1CH.Tehmovies.ir.mkv",
"duration": "05:32:26"
}
]
}
]
我只想返回 movies 的值。像这样
[
{
"name": "Guardians of the Galaxy",
"thumbnail": "https://nerdist.com/wp-content/uploads/2016/08/Guardians-of-the-Galaxy-poster-2.jpg",
"source_url": "http://dl.tehmovies.org/94/10/Star.Wars/Star.Wars.Episode.II.Attack.of.the.Clones.2002.1080p.5.1CH.Tehmovies.ir.mkv",
"duration": "05:30:09"
},
{
"name": "Star Wars II",
"thumbnail": "https://images-na.ssl-images-amazon.com/images/I/51TEG6X589L.jpg",
"source_url": "http://dl.tehmovies.org/94/10/Star.Wars/Star.Wars.Episode.II.Attack.of.the.Clones.2002.1080p.5.1CH.Tehmovies.ir.mkv",
"duration": "05:32:26"
}
]
我们将不胜感激。
请您参考如下方法:
根据您的帖子,serializer.data 返回
[
{
"movies": [
{
"name": "Guardians of the Galaxy",
"thumbnail": "https://nerdist.com/wp-content/uploads/2016/08/Guardians-of-the-Galaxy-poster-2.jpg",
"source_url": "http://dl.tehmovies.org/94/10/Star.Wars/Star.Wars.Episode.II.Attack.of.the.Clones.2002.1080p.5.1CH.Tehmovies.ir.mkv",
"duration": "05:30:09"
},
{
"name": "Star Wars II",
"thumbnail": "https://images-na.ssl-images-amazon.com/images/I/51TEG6X589L.jpg",
"source_url": "http://dl.tehmovies.org/94/10/Star.Wars/Star.Wars.Episode.II.Attack.of.the.Clones.2002.1080p.5.1CH.Tehmovies.ir.mkv",
"duration": "05:32:26"
}
]
}
]
使用简单的列表索引。 serializer.data 返回一个包含一个元素的列表。因此,要获得它,您可以调用 serializer.data[0]。该元素是一本字典。因此,要访问它,只需使用 serializer.data[0]["movies"]。这表示,“嘿 python,我想要这个列表的第一个元素 (serializer.data),然后从那个元素开始......哦,它是一个 dict。我可以用一个键来获得这个项目吗“电影”。“
