Django 标签 : why annotate(same_tags=Count ('tags' )) counts the number of common tags instead of the total number of tags?

标签 django

Django 2 by Example 中的教程,我不明白:

step (2): Why is `Count('tags')` **not** counting 
the total number of tags possessed by that post?

这段代码:

# List of similar posts
post_tags_ids = post.tags.values_list('id', flat=True)
similar_posts = Post.published.filter(tags__in=post_tags_ids)\
                              .exclude(id=post.id)
similar_posts = similar_posts.annotate(same_tags=Count('tags'))\
                             .order_by('-same_tags','-publish')[:4]

这样做:

  1. 通过查看相似的标签来搜索相似的帖子。
  2. 使用 Count 聚合函数生成计算字段 same_tags
  3. 按共享标签的数量降序排列结果......

我搜索了 Taggit 的 API 引用,但它似乎不相关。

最佳答案

I don't understand step (2): Why is Count('tags') not counting the total number of tags possessed by that post?

因为 .annotate(..) 子句 .filter(..) 子句之后使用。因此,您首先过滤连接的模型,然后计算仍然保留的元素。

aggregation section of the documentation 中所述:

When used with an annotate() clause, a filter has the effect of constraining the objects for which an annotation is calculated. For example, you can generate an annotated list of all books that have a title starting with “Django” using the query:

>>> from django.db.models import Avg, Count
>>> Book.objects.filter(name__startswith="Django").annotate(num_authors=Count('authors'))

因此您创建了一个如下所示的查询:

SELECT post.*
       COUNT(tag.id) AS same_tags
FROM post
INNER JOIN tag
WHERE tag.id IN <i>list_of_tag_ids</i>
  AND post.id != <i>id_of_post</i>
ORDER BY same_tags DESC, post.publish DESC

关于Django 标签 : why annotate(same_tags=Count ('tags' )) counts the number of common tags instead of the total number of tags?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61138562/

相关文章:

django - 通过相关对象链接查询

django - django rest 框架序列化程序中的 id 字段

python - 如何在 Django 中从查询集中删除而不删除原始模型本身

javascript - 如何编写双重嵌套 for 循环的计数代码?

Django - 如何重新创建或导入 django admin 绿色加号以添加新的相关实例?

django - 在 Django 中直接访问模板中设置的 ForeignKey

python - 在 OSX 上运行 django

django rest框架和表单: How to do

django信号模块对象没有属性connect

python - Django:使用GET(而不是PATCH)更新特定字段