以下に定義された todo モデルがあります。
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")
不完全なすべてのアクションをリストしたい:
actions = Action.objects.filter(complete=False)
アクションリストの私のテンプレートループ:
{% 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 %}
django-debug-toolbarを使用すると、すべてのアクションについて、{% if action.reoccurance %} および {% for tag in action.tags.all %} でデータベースにアクセスしていることがわかります。
ループの反復ごとにデータベースがpingされないように、クエリを作成するより良い方法はありますか? select_related と関係があると思いますが、django-taggitをどうすればいいのかわかりません。
更新私は私の答えの一部を得ました。select_related は機能しますが、おそらくタグに使用できないため、再発生を指定する必要がありました。
actions = Action.objects.select_related('reoccurance').filter(complete=False)
テンプレートループ内のすべての「action.tags.all」に対してデータベースにヒットするという問題はまだ残っています。django-taggit である種のプリフェッチを使用することは可能ですか?