开发者

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

开发者 https://www.devze.com 2023-02-28 10:14 出处:网络
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.

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 clo开发者_运维技巧se 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.


One option is to try and get all the user fields using the double underscore notation, so for example you could do something like values('user_username', 'user_someOtherField'). I'm not sure about getting the entire user object perhaps someone else can be of more help with that.

0

精彩评论

暂无评论...
验证码 换一张
取 消