zinon
zinon

Reputation: 4664

Django view: Count specific value from model

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?

Upvotes: 1

Views: 130

Answers (1)

AKS
AKS

Reputation: 19811

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.

Upvotes: 2

Related Questions