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 of the actions that are incomplete:
actions = Action.objects.filter(complete=False)
My template loops of the actions list:
{% 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 django-debug-toolbar, I see that for every action, I'm hitting the database on {% if action.reoccurance %} and {% for tag in action.tags.all %}.
Is there a better way to write my query so that the database isn't pinged for every iteration of the loop? I think it has something to do with select_related, but I'm not sure what to do about django-taggit.
Update I got part of my answer. select_related does work, but I had to specify reoccurance, probably because I can't use it for tags:
actions = Action.objects.select_related('reoccurance').filter(complete=False)
The problem still remains that I hit the database for every "action.tags.all" in the template loop. Is it possible to use some sort of prefetch on django-taggit?