1

In a django view I have:

 signed_by = Demographic.objects.all().values_list('data_entered_by')

And I get [(u'Patient',),(u'Patient',), (u'Other',)].

I want to count all that have Patient value and all that have Other value respectively.

In case I use

signed_by.count() 

I get the count for all. How do I count a specified value?

1 Answer 1

2

You can annotate the queryset:

signed_by = Demographic.objects.values('data_entered_by').annotate(cnt=Count('id'))

As a result you can get count for each data_entered_by value as follows, since it return a list of dict object:

for q in signed_by:
    print(q['data_entered_by'], q['cnt])

From the documentation:

When an annotate() clause is specified, each object in the QuerySet will be annotated with the specified values.

Sign up to request clarification or add additional context in comments.

6 Comments

What is the meaning of the annotate()?
I want to get a number for each.
I added what annotate does. It is used to annotate each object in a queryset with certain computed fields. I don't understand this part from your comments though ... I want to get a number for each ?
And I case I want to print the cnt value for each of them, how will I do it?
OK, great! Thanks! You answer is really helpful!
|

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.