Django,重复一个相关查询时多个数据库命中

Django, multiple DB hits when repeating one related query

这是型号:

class Category(models.Model):
    name = models.TextField()

class Post(models.Model):
    category = models.ForeignKey(Category)

现在,我想获取类别的帖子:

category = Category.objects.get(id=1)

posts = category.post_set.all()
# this line hit the DB

posts = category.post_set.all()
# and this line hit the DB again!

如何在这些关系中使用缓存的结果。我使用 Django rest-framework,它使每个实例的数据库命中多次。

您可以使用 .prefetch_related(…) [Django-doc]:

category = Category.objects<strong>.prefetch_related('posts')</strong>.get(id=1)

这将加载相关对象,并将在 Django/Python 层进行 JOINing。因此,这意味着 .all() 调用将使用预取对象。