I have a todo model defined below:
class Action(models.Model): name = models.CharField("Action Name", max_length=200, unique = True) complete = models.BooleanField(default=False, verbose_name="Complete?") reoccurance = models.ForeignKey(Reoccurance, blank=True, null=True, verbose_name="Reoccurance") notes = models.TextField("Notes", blank=True) tags = TaggableManager() class Reoccurance(models.Model): label = models.CharField("Label", max_length=50, unique = True) days = models.IntegerField("Days")
I want to list all the pending actions:
actions = Action.objects.filter(complete=False)
My template action list loops:
{% for action in actions %} <p>{{ action }}</p> {% if action.reoccurance %} <p>{{ action.reoccurance }}</p> {% endif %} {% for tag in action.tags.all %} <span>{{ tag }}</span>{% if not forloop.last %}, {% endif %} {% endfor %} {% endfor %}
Using the django-debug-toolbar , I see that for each action I click on the database with {% if action.reoccurance%} and {% for the tag in action.tags.all%}.
Is there a better way to write my query so that the database does not ping for each iteration of the loop? I think this has something to do with select_related, but I'm not sure what to do with django-taggit .
Update I received part of the response. select_related really works, but I had to specify reoccurance, perhaps because I cannot use it for tags:
actions = Action.objects.select_related('reoccurance').filter(complete=False)
The problem still is that I ended up in the database for each "action.tags.all" in the template loop. Is it possible to use some prefetching on django-taggit?