Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django "group by" via annotations: Get object from .value() vs. an ID

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?

like image 795
mitchf Avatar asked Apr 23 '11 03:04

mitchf


1 Answers

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.

like image 189
TinyTim Avatar answered Sep 25 '22 15:09

TinyTim