如果另一个表中存在行,请添加一个布尔字段? [英] Add a boolean field if a row exists in another table?
问题描述
我有两张表称为 Post
和回复
。用户可以为每个 Post
创建一个 Response
。模型如下所示:
I have two tables called Post
and Reply
. The users can create just one Response
for each Post
. The models look like this:
class Post(models.Model):
name = models.CharField(max_length = 100)
class Reply(models.Model):
post = models.ForeignKey(Post, related_name = 'replies')
现在,我有一个视图返回帖子,如下所示:
Now, I have a view that returns the posts, like this:
class PostList(generics.ListAPIView):
permission_classes = (permissions.IsAuthenticated,)
queryset = Post.objects.all()
serializer_class = PostSerializer
和一个序列化器的帖子:
And a serializer for the posts:
class PostSerializer(serializers.ModelSerializer):
class Meta:
fields = ('id', 'name')
此视图的结果如下所示:
The results of this view look like this:
[
{
"id": "1",
"name": "The first post"
},
{
"id": "2",
"name": "The second post"
}
]
现在,对于有问题的实际问题:如果用户已经回复了这篇文章,那么我想在结果中有一个布尔型字段,这个字段将是 true
,而 false
如果没有。基本上,当前用户已经回复到第一个帖子而不是第二个帖子的情况的结果将如下所示:
Now, to the actual problem in question: I'd like to have a boolean field in the results that'd be true
if the user has replied to the post, and false
if they hasn't. Basically, the result for a situation where the current user has replied to the first post but not the second post would look like this:
[
{
"id": "1",
"name": "The first post",
"replied": "true"
},
{
"id": "2",
"name": "The second post",
"replied": "false"
}
]
如何实现?我有一个希望,这应该在序列化器中实现,但我不知道该怎么做。
How do I achieve this? I have a hunch that this should be implemented in the serializer somehow, but I don't know how I'd do that.
提前感谢所有的帮助!
Thanks in advance for all your help!
推荐答案
在这里捎带dydek的答案。
Piggybacking off of dydek's answer here.
您覆盖在Api视图中 get_queryset
You overwrite your get_queryset in the Api View
class PostList(generics.ListAPIView):
...
def get_queryset(self):
Post.objects.all().extra(select={
'current_user_replies_count': 'SELECT COUNT(*) FROM <reply table> WHERE' +
'post_id=posts_post.id AND owner_id = %s'
},select_params=(request.user.id,))
current_user_replies_count'作为查询器中Post对象的属性。
This will add 'current_user_replies_count' as a property to the Post objects in your queryset.
这篇关于如果另一个表中存在行,请添加一个布尔字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!