Skip to content
Advertisement

Django Querysets adding additional information inside View

I’m currently working on a small django application for my school. I got two models involved in this problem: “category” and “device”, which are connected in a one-to-many relationship category—<device(s)

I added one page/template/view for the category overview, containing a large table with all the relevant information on every category created.

Querying the categories like this:

categories = Category.objects.filter(is_activ=True)

And displaying them inside the template like this:

{% for category in categories %}
{{ category.title }}
{{ category.otherField }}
{% endfor %}

is no Problem.

The Issue:

Now I need to add an extra field to the table containing the amount of devices in the category. Since the amount of devices is no field in my category model, but can rather be determined like this:

amount_devices_in_c1 = Device.objects.filter(category=c1).count()

it’s not possible for me to access the amount in the template by just doing:

{{ category.amount }}

Solution? Since adding a field to the category model is not an option and makes the code even less agile, I am loooking for a way to join/merge the information to the categories Queryset.

I guess it’s a pretty basic question, but I think I am missing some basic knowledge on Querysets/Mege/Join.

Advertisement

Answer

You can use annotate to add additional information to your queryset:

from django.db.models import Count

categories = Category.objects.filter(is_activ=True).annotate(device_count=Count('device_set'))

Now in the template you can write {{ category.device_count }}.
Replace device_set with the related name if you have set any.

Advertisement