python - 缓存或预取 Django 的反向关系

标签 python django prefetch

考虑一个带有 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/

相关文章:

html - 使用 HTML5 预取的危险?

c - 一次性从磁盘读取一组离散的页面

python Json递归渲染为html

python - 为什么 numpy.fromstring 读取数字是错误的?

python - 如何将 tuple1 if ... else tuple2 传递给 str.format?

python - unittest.TestCase.assertEqual 的参数顺序

python - Django:保存到 ModelForm 的 save() 方法中的多对多字段?

python - 如何修复 virtualenvwrapper_run_hook :12: and virtualenvwrapper. sh 问题...?

python - 如何在 django rest 框架中反转 ViewSet 自定义操作的 URL

python - 从 Tensorflow PrefetchDataset 中提取目标