I'm trying to do the equivalent of a "group by" to pull a list of all Guesses on a Quiz owner's quizzes, grouped by user and annotated with a count of how many guesses that user has made.
Relevant models:
class Quiz(models.Model):
user = models.ForeignKey(User)
...
class Guess(models.Model):
user = models.ForeignKey(User)
quiz = models.ForegnKey(Quiz)
...
This query:
guessors = Guess.objects.filter(quiz__user=request.user).values('user').annotate(cnt=Count('user')).order_by('cnt')
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 'user' is returned as an int when what I want is as a full User object. Any suggestions as to how I should most efficiently get the full User object?
In my short but intense time with Django, I've found that the group_by function is one of the SQL features that I miss the most. I have tried the values() aggregation method you used above, but had the same problem where I wanted an object returned. I ended up using raw SQL, which wasn't pretty but worked for what I needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With