我是django restframework的新成员 我有一个关于如何在django restframework
中获取外键值的问题我的代码如下,当我想使用django restframework来编写json时。
models.py:
class Movie(models.Model):
link = models.URLField()
title = models.CharField(max_length=255, null=True)
class MovieImage(models.Model):
movieimage = models.ForeignKey(Movie,null=True,blank=True)
img_link = models.URLField(max_length=255, null=True)
img_describe = models.URLField(max_length=255, null=True)
img_rank = models.URLField(max_length=255, null=True)
serializers.py
class MovieSerializer(serializers.ModelSerializer):
images = serializers.RelatedField(many=True, read_only=True, source='movieimage_set')
class Meta:
model = Movie
fields = ('link', 'title', 'images')
我会得到结果:
{
"link": "https://test.com/id=1",
"title": "TEST",
"images": [
"MovieImage object"
]
}
我想知道如何在类images
中显示变量,如:
{
"link": "https://test.com/id=1",
"title": "TEST",
"images"[img_describe: "img_describe value",
img_link: "img_link vlaue" ]
}
答案 0 :(得分:2)
如果您只需要images
是只读的,则可以使用嵌套的序列化程序执行此操作。如果它必须是可写的,则可能存在一些问题,因为嵌套序列化器在DRF中写入时存在问题< 3.0,尤其是像这样的多对多案例。
您必须为图像编写序列化程序,类似于:
class MovieImageSerializer(serializers.ModelSerializer):
img_link = serializers.URLField()
img_describe = serializers.CharField()
class Meta:
model = MovieImage
fields = ('img_link', 'img_describe', )
并将其添加到当前序列化程序中作为字段的替代,类似于:
class MovieSerializer(serializers.ModelSerializer):
images = MovieImageSerializer(many=True, read_only=True, source='movieimage_set')
class Meta:
model = Movie
fields = ('link', 'title', 'images')
这将为您提供具有嵌套对象的输出,类似于:
{
"link": "https://test.com/id=1",
"title": "TEST",
"images": [
{
"img_describe": "the value",
"img_link": "a link"
}
]
}
您可以在Django REST Framework documentation中找到有关嵌套关系的更多信息。