考虑一个带有 Publishers 表和 Books 表的 shema,这样
def Publisher(models.Model):
city = models.CharField()
...
def Book(models.Model):
title = models.CharField()
publisher = models.ForeignKey(Publisher)
在我的模板中,我希望显示某些出版商及其所有书籍的列表。在我的 View 函数中,我使用类似的东西获取所需的发布者
publishers=Publisher.objects.filter(city='NY')
然后在我看来,我会像这样迭代 publishers 和 publishers.book_set.all
{% for p in publishers %}
....
{% for b in p.book_set.all %}
这按预期工作,除了它显然像无数次一样命中数据库。
如何优化代码,使 django 只访问数据库一次或两次?
最佳答案
在 Django 1.4+ 中,使用 prefetch_related
Publisher.objects.filter(city='NY').prefetch_related('book_set')
在 Django <1.4 中,使用 django-batch-select .
关于python - 缓存或预取 Django 的反向关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13033716/