django - 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})
解决方案
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
推荐阅读
- google-sheets - 根据 Google 表格中的第一个单元格格式化列中的单元格
- elasticsearch - Openstack 实例上的 Elasticsearch 7 无法设置 ES 集群
- firebase - 从 firebase 功能重定向到 paypal 结帐不起作用
- directx-9 - 如何使用 ASSIMP 将 .obj 文件加载到 DirectX9
- python - 如何在 django 的一个视图中运行不同的操作,在 HTML 页面上按下两个不同的按钮
- python - python tuple 仅打印键名
- angular - 如何将不同的数据集与 Angular 7 中的多个组件相关联?
- python-3.x - 如何在 Python Tkinter 中将条目移动到靠近标签的位置
- r - 如何将此数据结构转换为矩阵?
- visual-studio-2019 - 为什么 Visual Studio 链接器会抱怨找不到 CreateBkColor