0

I have two models Post and Tag(given by django-taggit app). So they make use of generic foreign key concept.

If i query posts like:

posts = Post.objects.annotate(num_tags=Count('tags'))

and try to retrieve value of num_tags for first result in queryset like:

posts[0].num_tags
>> 7 (which is true, there are 7 tags related with this post)

Now, say if i have a post with tag ids = [4,5,6] and I query similar posts to this one like:

similar_posts = Post.objects.filter(tags__in=tag_list).annotate(num_tags=Count('tags'))

Now, if I try to retrieve the num tags value like:

similar_posts[0].num_tags
>> 1

Here 1 is referring to the number of tags that matched from the tag list. But why does Django not explain this behavior anywhere in their documentation, or am i missing some parts of documentation? Can someone please explain the actual working of 'annotate' and 'count' in different scenarios?

Note: similar_posts[0] and posts[0] is the same object.

I was expecting the num_tags to show 7 in both cases. However showing 1 in the latter case actually helps in my usecase. But need to know why does Count behave differently in the latter case.

0 Answers0