所以我有这个序列化器
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),并从该元素中.... OOH,它是一个dict
。我能否拥有一个键为"movies"
的项目。 ”关于python - 在DjangoRestFramework中不带键的情况下返回“ReturnList”的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48392601/