127👍
✅
I think Count('topics', distinct=True)
should do the right thing. That will use COUNT(DISTINCT topic.id)
instead of COUNT(topic.id)
to avoid duplicates.
User.objects.filter(
username_startswith="ab").annotate(
posts=Count('post', distinct=True)).annotate(
topics=Count('topic', distinct=True)).values_list(
"username","posts", "topics")
0👍
Try adding distinct to your last queryset:
User.objects.filter(
username_startswith="ab").annotate(
posts=Count('post')).annotate(
topics=Count('topic')).values_list(
"username","posts", "topics").distinct()
See https://docs.djangoproject.com/en/1.3/ref/models/querysets/#distinct for more details, but basically you’re getting duplicate rows because the annotations span multiple tables.
- [Django]-How to get the label of a choice in a Django forms ChoiceField?
- [Django]-How to resize an ImageField image before saving it in python Django model
- [Django]-How do I do a not equal in Django queryset filtering?
Source:stackexchange.com