简体   繁体   English

如果在 ManyToManyField 中的 object,如何注释查询集

[英]How to annotate queryset if object in ManyToManyField

I am trying to build a small social network where users can like posts.我正在尝试建立一个小型社交网络,用户可以在其中喜欢帖子。 I am using Django 3.1.7.我正在使用 Django 3.1.7。 I have defined my model for the post as follows:我为帖子定义了我的 model,如下所示:

class Post(models.Model):
    date_published = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.CharField(max_length=240, blank=False, default=None)
    user_like = models.ManyToManyField(User, blank=True, related_name='likes')

    def __str__(self):
        return f'{self.user.username} posted \"{self.content}\" on {self.date_published}'

From my views.py I want to return the posts with an annotation of whether the current user has liked a given post.从我的views.py中,我想返回带有当前用户是否喜欢给定帖子的注释的帖子。 I am trying as follows:我正在尝试如下:

def index(request):

    posts = Post.objects.all().annotate(
        likes=Count('user_like')).order_by('-date_published')

    if request.user.is_authenticated:
        posts = Post.objects.all().annotate(
            likes=Count('user_like'), liked=request.user in 'user_like'.all).order_by('-date_published')
    
    paginator = Paginator(posts, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    return render(request, "network/index.html", {
        'post_form': PostForm(),
        'page_obj': page_obj
    })

But unfortunately, I can not make the query work.但不幸的是,我无法使查询工作。 I assume that the part where I check if the user is in the relationship is wrong ( liked=request.user in 'user_like'.all ) as it is treating 'user_like' as str and not as the field in the Post.我假设我检查用户是否处于关系中的部分是错误的( liked=request.user in 'user_like'.all ),因为它将'user_like'视为str而不是 Post 中的字段。

How should I annotate the posts to include whether the user has liked them or not based on the ManyToManyField between them?我应该如何根据它们之间的ManyToManyField注释帖子以包括用户是否喜欢它们? Thanks谢谢

You can work with an Exists subquery [Django-doc] :您可以使用Exists子查询[Django-doc]

from django.db.models import Exists, OuterRef

posts = Post.objects.annotate(
    likes=Count('user_like'),
    liked=Exists(Post.user_like.through.objects.filter(
        post_id=OuterRef('pk'),
        user_id=request.user.pk
    ))
).order_by('-date_published')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM