Skip to content

Instantly share code, notes, and snippets.

@chrischambers
Created September 9, 2010 18:27
Show Gist options
  • Save chrischambers/572284 to your computer and use it in GitHub Desktop.
Save chrischambers/572284 to your computer and use it in GitHub Desktop.
# I need the best idiomatic way of getting a map of users and their points.
# The values/annotation combo *almost* gives me what I want, but doesn't return
# full user objects, only their ids.
>>> Points.objects.values('user').annotate(total_points=Sum('amount'))
[{'total_points': 40, 'user': 1}, {'total_points': 30, 'user': 2}]
# I've opted for something like this, instead:
Points.objects.users().annotate(total_points=Sum('points__amount'))
# and the method, on the QuerySet/Manager:
def users(self):
user_ids = self.values_list('user', flat=True)
return User.objects.filter(id__in=user_ids)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment