gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:31:37 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com