1๐
โ
You can do the count from your User
model instead (the code is more intuitive) using annotate
with in_bulk
from django.db.models import Count
user_ids = [user.id for user in context["object_list"]]:
users = User.objects.annotate(photo_count=Count('photo', distinct=True)).in_bulk(user_ids)
Then, you can build your list doing:
users_photo_count = [(id, users[id].photo_count) for id in user_ids]
# [(1, 20), (2, 39), (3, 45). . .]
๐คMoses Koledoye
0๐
You can do this with annotate
with values_list()
As you expect the output is list of tuples with user_id and their photos uploaded count
from django.db.models import Count
user_ids = [user.id for user in context["object_list"]]
user_photos = Photo.objects.filter(owner_id__in=user_ids).values('owner').annotate(Count('owner')).values_list('owner', 'owner__count')
# user_photos = [(1, 31), (2, 41), (3, 12)......]
๐คMani
- How to compare data in SQL
- Django: defining a generic manager in an Abstract model
- How to use variable from looping as dictionary key in Django template?
- Django-datatable default iDisplayLength
Source:stackexchange.com