我想了解在django中構建查詢以避免過多數據庫命中的最佳方法。
這與問題類似:Django best practice with foreign key queries,但在查詢中涉及更大的「深度」。django最佳做法查詢外鍵
我的情況: models.py
class Bucket(models.Model):
categories = models.ManyToManyField('Category')
class Category(models.Model):
name = models.CharField(max_length=50)
class SubCategory(models.Model):
category = models.ForeignKey(Category)
class SubSubCategory(models.Model):
subcat = models.ForeignKey(SubCategory)
views.py
def showbucket(request, id):
bucket = Bucket.objects.prefetch_related('categories',).get(pk=id)
cats = bucket.categories.prefetch_related('subcategory_set__subsubcategory_set',)
return render_to_response('showbucket.html', locals(), context_instance=RequestContext(request))
和相關模板:
{% for c in cats %}
{{c}}
<ul>
{% for d in c.subcategory_set.all %}
<li>{{d}}</li>
<ul>
{% for e in d.subsubcategory_set.all %}
<li>{{e}}</li>
{% endfor %}
</ul>
{% endfor %}
</ul>
{% endfor %}
儘管使用prefetch_related(),我似乎每次評估語句的前兩位時都要打到數據庫,例如{%for c in cats%},(至少我相信通過閱讀debug_toolbar)。我嘗試過的其他方式以(C x D x E)數量的數據庫命中結束。這是我使用預取,查詢或模型時固有的錯誤嗎? Django以「深度> 1」的方式訪問數據庫對象的最佳方式是什麼?