I'm trying to make the equivalent of "group by" to get a list of all Guesses in the Quiz owner polls grouped by user and annotated by counting the number of guesses made by the user.
Relevant models:
class Quiz(models.Model):
user = models.ForeignKey(User)
...
class Guess(models.Model):
user = models.ForeignKey(User)
quiz = models.ForegnKey(Quiz)
...
This request:
guessors = Guess.objects.filter(quiz__user=request.user).values('user').annotate(cnt=Count('user')).order_by('cnt')
It returns something like this, which is very close to what I need:
{'cnt': 5, 'user': 5}
{'cnt': 3, 'user': 4}
{'cnt': 2, 'user': 3}
{'cnt': 1, 'user': 2}
Note, however, that the “user” is returned as int when what I want is the complete user object. Any suggestions on how I should most efficiently get the complete User object?
source
share