2

I have the following model:

class Pick(models.Model):
league = models.ForeignKey(League)
user = models.ForeignKey(User)
team = models.ForeignKey(Team)
week = models.IntegerField()
result = models.IntegerField(default=3, help_text='loss=0, win=1, tie=2, not started=3, in progress=4')

I'm trying to get generate a standings table based off of the results, but I'm unsure how to get it done in a single query. I'm interested in getting, for each user in a particular league, a count of the results that = 1 (as win), 0 (as loss) and 2 as tie). The only thing I can think of is to do 3 separate queries where I filter the results and then annotate like so:

Pick.objects.filter(league=2, result=1).annotate(wins=Count('result'))
Pick.objects.filter(league=2, result=0).annotate(losses=Count('result'))
Pick.objects.filter(league=2, result=2).annotate(ties=Count('result'))

Is there a more efficient way to achieve this?

Thanks!

1 Answer 1

1

The trick to this is to use the values method to just select the fields you want to aggregate on.

Pick.objects.filter(league=2).values('result').aggregate(wins=Count('result'))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply, although I'm afraid I don't quite see how using values will help me get down to a single query for wins, losses and ties. Would you mind expanding your example a bit more?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.