我正在尝试使用Django Rest-Framework来生成一些JSON,以显示用户的所有帖子,还显示该帖子的图像。图片是Post的外键。这是模型:
models.py
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
status = models.CharField(max_length=200)
class Image(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
img = models.CharField(max_length=120)
views_count = models.IntegerField(default=0)
views.py
class GetPosts(ListAPIView):
serializer_class = PostSerializer
def get_queryset(self):
requested_user = get_requested_user(self)
return Post.objects.filter(user=requested_user).order_by('-created_at')
def get_requested_user(self):
filter_kwargs = {'username': self.kwargs['username']}
return get_object_or_404(User.objects.all(), **filter_kwargs)
serializers.py
class PostSerializer(serializers.ModelSerializer):
image_img = serializers.RelatedField(source='Image', read_only=True)
class Meta:
model = Post
fields = ('status', 'image_img ')
在serializers.py中,我想显示所有图片(img, views_count
)字段,我在当前代码中得到的是:
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"status": "I am number 1"
}
]
}
其中包含用户的帖子,但不包含用户的帖子和每个帖子的图像。注意:查询网址如下:/ api / posts / user /
答案 0 :(得分:1)
您应该在此处使用 嵌套序列化程序 ,
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields = ('img',)
class PostSerializer(serializers.ModelSerializer):
image_img = ImageSerializer(source='image_set', many=True)
class Meta:
model = Post
fields = '__all__'
因此,响应将类似于
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"status": "I am number 1",
"image_img": [
{"img": "image_url"},
{"img": "image_url"},
....
]
}
]
}
如何在序列化器中显示模型类的
all
字段?
从doc,
您还可以将
fields
属性设置为特殊值'__all__'
,以指示 。
参考
1. DRF- Nested Realtions
2. source
argument
3. Specifying which fields to include