Home > Software design >  Django - accessing a count of a queryset filtered by specific value in my template
Django - accessing a count of a queryset filtered by specific value in my template

Time:05-10

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

{% regroup programmes by region as region_list %}
[…]
<div >
  {% for region in region_list %}
[...]
            <tr>
                <th scope="col">Programmes in {{region.grouper }} </th>
                <th scope="col">Registered partners</th>
                <th scope="col">Active</th>
            </tr>
            </thead>
            
            <tbody>
            {% for programme in region.list|dictsort:"programme"  %}
            <tr>
                <th scope="row">{{ programme }}</th> #name of programme in region in rows
                <td>{{ programme.PartofProgramme.all.count }}</td> #number of registered partners in programme
                <td> {{  ##get count of active partners## }}</td> #get number of partners with status__code=’active’
            </tr>
            {% endfor %}
            </tbody>
        </table>
  </div>
  {% endfor %}

views.py

class DevView(generic.ListView):
    template_name = "maindb/index_alt.html"
    model = Programme

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['programmes'] = Programme.objects.all().order_by('region')
        return context

models.py

class Region(models.Model):
    region = models.CharField(max_length=200)

class Programme(models.Model):
    programme = models.CharField(max_length=200)
    region = models.ForeignKey('Region', on_delete=models.SET_NULL, null=True, blank=True,  related_name="regions", verbose_name="Region")

class TagStatus(models.Model):
    code = models.CharField(max_length=20)
    field = models.CharField(max_length=100, null=False)

class Partner(models.Model):
    name = models.CharField(max_length=200)
    programme = models.ForeignKey('Programme', on_delete=models.SET_NULL, null=True, blank=True,    related_name="PartofProgramme")
    status = models.ForeignKey('TagStatus', on_delete=models.SET_NULL, null=True, blank=True)

CodePudding user response:

I think easy way is to provide filtered queryset in context in get_context_data.

`context['active_partners'] = Programme.PartofProgramme.filter(status__code="active")`

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

Example:

@register.filter
def status_active_count(partners):
    return partners.filter(status__code="active").count()
  • Related