Django:在变量或方法中保存多个 Prefetch() 对象

标签 django prefetch

documentation显示如何将 Prefetch() 对象保存在变量中:

>>> prefetch = Prefetch('choice_set', queryset=voted_choices, to_attr='voted_choices')
>>> Question.objects.prefetch_related(prefetch).get().voted_choices
[<Choice: The sky>]

但是,prefetch_related 接受许多用逗号分隔的 Prefetch() 对象:

>>> Question.objects.prefetch_related(Prefetch('choice_set'), Prefetch('foo')).get().voted_choices

如何将这个 Prefetch() 序列保存在一个变量中 - 或者甚至更好地保存在一个方法中 - 以便可重用?

最佳答案

我更喜欢在自定义 QuerySet 中添加这些与 Prefetch 相关的子句,然后通过模型属性访问创建的列表(如果存在)。

用法:Post.objects.filter(...).prefetch_comments()...

class PostQuerySet(models.QuerySet):
    def prefetch_comments(self):
        inner_qs = Comment.objects.order_by('-date')
        return self.prefetch_related(Prefetch("comments", queryset=inner_qs, to_attr="comments_list"))


class Post(models.Model):
    ....
    objects = PostQuerySet.as_manager()

    @property
    def most_recent_comment(self):
        if hasattr(self, 'comments_list') and len(self.comments_list) > 0:
            return self.comments_list[0]
        return None

关于Django:在变量或方法中保存多个 Prefetch() 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31596954/

相关文章:

python - 使用我的 django 应用程序中另一个模块的模板文件夹

python - 如何通过 CQL 直接连接 Cassandra 的示例 (1)

html - 在 HTML 中设置新的预呈现或预取的正确方法是什么?

email - 防止预取电子邮件中的链接

assembly - PREFETCH 和 PREFETCHNTA 指令之间的区别

vue.js - Lazy Route 被预取,忽略 webpack 魔法注释 (Vue)

Django:使用 ForeignKey 注释对象的计数/总和 - 错误输出

javascript - Django:在不重定向的情况下更新页面信息

python - Django 报错邮件 : env vars leak info

提前打字,猎犬 : remote works but not prefetch