filter tags of django-taggit in Django's Queryset

匆匆过客 提交于 2019-12-02 12:45:50

Django is counting only the python and data tags which you included in your filter clause - other tags are not counted. (Note that the only example with sam_tags of 2 is the one tagged both data and python.) This is probably unexpected behavior, but makes sense if you consider how the underlying SQL is executed. See this example from a similar schema to yours:

>>> a = Article.objects.filter(tags__slug__in=['python']).annotate(num_tags=Count('tags'))[0]
>>> a.num_tags
1
>>> a.tags.count()
2

If I change the filter clause to filter on somethign other than tags, it behaves as expected:

>>> Article.objects.filter(pk=a.pk).annotate(num_tags=Count('tags'))[0].num_tags
2
>>> Article.objects.filter(pk=a.pk).annotate(num_tags=Count('tags'))[0].tags.count()
2

it's relatively straight forward to look into the query by print(similar_post.query) we can see the code only counts the tag_id which belongs to the tags of the post is being shown.

SELECT "blog_post"."id", "blog_post"."title", "blog_post"."slug", "blog_post"."author_id", "blog_post"."body", "blog_post"."publish", "blog_post"."created", "blog_post"."updated", "blog_post"."status", COUNT("taggit_taggeditem"."tag_id") AS "same_tags" FROM "blog_post"

INNER JOIN "taggit_taggeditem" ON ("blog_post"."id" = "taggit_taggeditem"."object_id" AND ("taggit_taggeditem"."content_type_id" = 7))

WHERE ("blog_post"."status" = published

   AND "taggit_taggeditem"."tag_id" IN (SELECT DISTINCT U0."id" FROM "taggit_tag" 
                                                        U0 INNER JOIN "taggit_taggeditem" U1 ON (U0."id" = U1."tag_id") 
                                                        INNER JOIN "django_content_type" U2 ON (U1."content_type_id" = U2."id") 
                                                        WHERE (U2."app_label" = blog AND U2."model" = post AND U1."object_id" = 8)) 

   AND NOT ("blog_post"."id" = 8)) 

GROUP BY "blog_post"."id", "blog_post"."title", "blog_post"."slug", "blog_post"."author_id", "blog_post"."body", "blog_post"."publish", "blog_post"."created", "blog_post"."updated", "blog_post"."status"

ORDER BY "same_tags" DESC, "blog_post"."publish" DESC LIMIT 4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!