Skip to content
Advertisement

Django – accessing a count of a queryset filtered by specific value in my template

I had problems even formulating the title to this question :) I am very much a beginner in everything coding but am enjoying learning through a Django project. Usually I can go bit by bit solving my problems by searching around, but I have failed in the below and am stuck although I am certain there is an easy solution… In the below I am doing the following in my html code:

step 1. from my views I am getting the context ‘programmes’ sorted by field ‘region’ and use that to list for each region with a list of programmes belonging to the region using a for loop.

step 2. In the second column in the table for each programme I show count of total partners in database for that particular programme (using related_name ‘PartofProgramme’ for a foreignkey). So far so good and everyhting works fine.

step 3. When I check at this stage the ‘programme.Partof Programme.all’ contains a queryset as follows: “<QuerySet [<Partner: examplepartner1>, <Partner: examplepartner2>, etc etc. listing all partners belonging to the filtered programme. For the third column in the table I want to show a count of these partners with status__code value = ‘active’. How do I access this from my html template where it now says “##get count of active partners##” below?

Cuts from my code below.

index_alt.html

JavaScript

views.py

JavaScript

models.py

JavaScript

Advertisement

Answer

You can use custom filters.

Example:

JavaScript

You can read more here: https://docs.djangoproject.com/en/4.0/howto/custom-template-tags/#registering-custom-filters

Advertisement