0

I'm using annotate with my Django queryset to count a number of records. I am using it with filter and understand the order makes a difference.

My query is: numcontestants = Contestant.objects.filter(assigned_team__id=urlid).annotate(num_contestants=Count('id'))

When I pass numcontestants to my template and display it with {{ numcontestants }} I see a queryset containing each of the records I want to view. When I try with:

{{ numcontestants.num_contestants }} I get nothing.

I don't want to have to iterate over numcontestants to get a count, my understanding was that num_contestants should be a single integer number. Even so, iterating over doesn't give the result I am after, for example using:

{% for x in numcontestants %} {{x.num_contestants}} {% endfor %}

outputs 1 1 1 when I am trying to get something that will output 3.

What is the right way to generate and access a sum count?

1 Answer 1

1

annotate return a number for each record, you can get num_contestants for the first record:

{{ numcontestants.0.num_contestants }}

if you want to get a number of queryset results can use .count() in your quesyset

numcontestants = Contestant.objects.filter(assigned_team__id=urlid).count()
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh so simple, thank you. Everything I was reading on how to count records seemed to indicate count had to be used with annotate, I didn't realize I could use count directly on the queryset. Feel foolish for having missed something so obvious now.

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.