【问题标题】:Django, multiple DB hits when repeating one related query重复一个相关查询时,Django,多个数据库命中
【发布时间】:2021-10-23 03:09:54
【问题描述】:

这是模型:

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,它使 DB 为每个实例多次命中。

【问题讨论】:

    标签: python django django-rest-framework django-orm


    【解决方案1】:

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

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

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

    【讨论】:

    • 我在 drf 视图中使用 category = Category.objects.prefetch_related("post_set") get_queryset 函数并且它有效!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 2012-06-21
    • 2019-08-17
    • 1970-01-01
    • 2011-03-28
    相关资源
    最近更新 更多