[Fixed]-Tricky list processing in Django app

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

Leave a comment