首页 > 解决方案 > Count() 方法在这段代码中是如何工作的?

问题描述

我有这本书中的这段代码,我目前正在经历,不知道它是如何工作的。如果有人可以向我解释 Count('tags') 如何知道它应该只计算与帖子相关的标签,我会很高兴。

def post_detail(request, year, day, month, post):
    post = get_object_or_404(Post, slug = post, publish__year = year, publish__month = month, publish__day = day)
    comments = post.comments.filter(active=True)

    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.post = post
            new_comment.save()
    else:
        comment_form = CommentForm()

    post_tags_pks = post.tags.values_list('pk', flat=True)
    similar_posts = Post.published.filter(tags__in=post_tags_pks).exclude(pk=post.pk)
    similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:4]


    return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'comment_form': comment_form,'similar_posts': similar_posts})

标签: djangopython-3.xcount

解决方案


Django 聚合方法Count()django.db.models注解到通过 ForeignKey 计算与之相关的 Children 的数量。

你可以看看Django Aggregation

下面的代码将通过注释给出与各个帖子相关的所有标签的计数。

similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:4]

您可以使用存储计数的变量访问任何帖子的计数。

在您的情况下,以下代码将为第一篇文章提供标签计数。

similar_posts[0].same_tags

推荐阅读