65👍
Thanks for your comment. That didn’t quite work but it steered me in the right direction. I was finally able to solve this by adding distinct to both Count() calls:
Count('tourcomment', distinct=True)
👤tbak
4👍
tour_list = Tour.objects.all().annotate(tour_count=Count('tourcomment',distinct=True) ).annotate(history_count=Count('history',distinct=True) )
You have to add distinct=True
to get the proper result else it will return the wrong answer.
- [Django]-Django REST Framework (DRF): Set current user id as field value
- [Django]-Django-allauth social account connect to existing account on login
- [Django]-Django – how do I select a particular column from a model?
0👍
I can’t guarantee that this will solve your problem, but try appending .order_by()
to your call. That is:
tour_list = Tour.objects.all().annotate(Count('tourcomment')).annotate(Count('history')).order_by()
The reason for this is that django needs to select all the fields in the ORDER BY clause, which causes otherwise identical results to be selected. By appending .order_by()
, you’re removing the ORDER BY clause altogether, which prevents this from happening. See the aggregation documentation for more information on this issue.
- [Django]-Is it OK to use multiple inheritance with Django abstract models?
- [Django]-Django project base template
- [Django]-Troubleshooting Site Slowness on a Nginx + Gunicorn + Django Stack
Source:stackexchange.com