[英]how to get the value in the Foreign key in django restframework
I'm new in django restframework 我是Django Restframework的新手
I have a question about how to get the value in the Foreign key in django restframework 我有一个关于如何在Django restframework的外键中获取值的问题
My code is below,when I want to use django restframework to get write the json. 当我想使用Django restframework来编写json时,我的代码如下。
models.py: 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 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')
And I will get the results: 我会得到结果:
{
"link": "https://test.com/id=1",
"title": "TEST",
"images": [
"MovieImage object"
]
}
I want to know how to display the variable in class images
like: 我想知道如何在类
images
显示变量,例如:
{
"link": "https://test.com/id=1",
"title": "TEST",
"images"[img_describe: "img_describe value",
img_link: "img_link vlaue" ]
}
If you only need images
to be read-only, you can do this using a nested serializer. 如果只需要
images
是只读的,则可以使用嵌套的序列化程序来实现。 If it has to be writable, you may have some issues as nested serializers have problems with writing in DRF < 3.0, especially in many-to-many cases like this. 如果它必须是可写的,那么您可能会遇到一些问题,因为嵌套序列化器在DRF <3.0中编写时会遇到问题,尤其是在许多这样的情况下。
You would have to write a serializer for images, similar to this: 您将必须为图像编写一个序列化器,类似于:
class MovieImageSerializer(serializers.ModelSerializer):
img_link = serializers.URLField()
img_describe = serializers.CharField()
class Meta:
model = MovieImage
fields = ('img_link', 'img_describe', )
and add it to your current serializer as a replacement for the field, similar to this: 并将其添加到您当前的序列化器中,以代替该字段,类似于:
class MovieSerializer(serializers.ModelSerializer):
images = MovieImageSerializer(many=True, read_only=True, source='movieimage_set')
class Meta:
model = Movie
fields = ('link', 'title', 'images')
This will give you output with nested objects, similiar to this: 这将为您提供与嵌套对象类似的输出:
{
"link": "https://test.com/id=1",
"title": "TEST",
"images": [
{
"img_describe": "the value",
"img_link": "a link"
}
]
}
You can find more information on nested relationships in the Django REST Framework documentation . 您可以在Django REST Framework文档中找到有关嵌套关系的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.