我在下面定義的待辦事項模式:優化Django的查詢拉外鍵和Django的taggit關係
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 action in action.tags.all%}中。
有沒有更好的方式來編寫我的查詢,以便數據庫不會針對循環的每次迭代進行ping?我認爲它與select_related有關,但我不知道該怎麼做django-taggit。
更新我得到了我的答案的一部分。 select_related的工作,但我必須指定reoccurance,可能是因爲我不能用它來標記:
actions = Action.objects.select_related('reoccurance').filter(complete=False)
的問題仍然是我打的數據庫,每一個「action.tags.all」模板循環。是否有可能在django-taggit上使用某種預取?
感謝您的輸入。免責聲明可能是正確的:'QuerySet'對象沒有'prefetch_related'屬性。我是否應該接受,我將有一個數據庫,以便在行動中採取行動? –
我不能100%確定,因爲我從來沒有看過那個應用程序,但我的直覺告訴我,這隻能在字段上完成。現在,您可能可以在一個查詢中手動查詢所有標記,並使用該結果代替循環中每個對象的thr管理器。 – jdi