首页 > 解决方案 > 如何防止 Django 的 prefetch_related 缓存查询集

问题描述

对于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参数。问题是第二次预取不能正常工作,discomparation_reactions列表是空的。但如果我删除第一个预取,它会起作用。我相信第一个查询集,即View.objects正在以某种方式被缓存。我怎样才能防止这种情况?

标签: pythondjangodjango-rest-frameworkdjango-queryset

解决方案


根据Django文档,您可以通过:

queryset.prefetch_related(None)

因为它将清除任何 prefetch_related 行为

这是它的参考点击这里


推荐阅读