Reduce database hit when using django-taggit and mymodel.tags.all in a template

28 views Asked by At

I'm using django-taggit in Django 3.2 and can't figure out how to prevent it from hitting the database for every object in a list view template.

Here's how I'm using it:

class Quest(TagsModelMixin, models.Manager):
    # etc.

In a ListView html template, I am displaying all Quest objects and their tags like this:

{% for obj in quest_queryset %}
  {{obj.name}}: {{ obj.tags.all }}
{% endfor %}

At first, this was hitting the DB twice per object. I found that if I prefetch_related I could remove half of them:

quest_queryset = quest_queryset.prefetch_related('tags')

But I'm still getting one hit per object. How can I eliminate this repetition? Here's the offending query as shown by django-debug-toolbar, when there are 5 Quest objects.

enter image description here

0

There are 0 answers