【问题标题】:How to prevent Django's prefetch_related from caching a queryset如何防止 Django 的 prefetch_related 缓存查询集
【发布时间】:2021-08-25 10:08:49
【问题描述】:

我对 Argument 模型有以下查询集函数:

class ArgumentQuerySet(QuerySet):
    def prefetch_related_objects(self):
        from views.models import View

        return self.prefetch_related(
            Prefetch(
                'argument_reactions',
                queryset=View.objects.filter(type=ViewType.ARGUMENT_REACTION.name,
                                             reaction_type=ReactionType.ENDORSE.name),
                to_attr='endorsement_reactions'
            ),
            Prefetch(
                'argument_reactions',
                queryset=View.objects.filter(type=ViewType.ARGUMENT_REACTION.name,
                                             reaction_type=ReactionType.DISAGREE.name),
                to_attr='disagreement_reactions'
            ),
        )

如您所见,我正在尝试使用不同的查询集预取相同的关系,并且我还使用了 Prefetch 对象的 to_attr 参数。问题是第二次预取不能正常工作,disagreement_reactions 列表是空的。但如果我删除第一个预取,它会起作用。我相信第一个查询集,即 View.objects 正在以某种方式被缓存。我怎样才能防止这种情况发生?

【问题讨论】:

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


    【解决方案1】:

    根据Django文档,可以通过:

    queryset.prefetch_related(None)
    

    因为它会清除任何 prefetch_related 行为

    这是它的参考Click Here

    【讨论】:

    • 这是否意味着我添加了另一个 prefetch_related ?我的意思是之后:queryset.prefetch_related(None)。
    猜你喜欢
    • 2019-03-16
    • 1970-01-01
    • 2013-06-06
    • 2014-01-31
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    相关资源
    最近更新 更多