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

时间:2015-07-23 19:59:42

标签: 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()序列保存在变量中 - 或者在方法中更好 - 以便可重用?

1 个答案:

答案 0 :(得分:4)

我更喜欢在自定义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