简体   繁体   中英

How to prevent Django's prefetch_related from caching a queryset

I have the following queryset function for an Argument model:

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'
            ),
        )

As you can see I'm trying to prefetch the same relation using different querysets and I'm also using the to_attr parameter of the Prefetch object. The problem is the second prefetch is not working properly, the disagreement_reactions list is empty. But it works if I remove the first prefetch. I believe the first queryset, ie, View.objects is being cached somehow. How can I prevent that?

According to Django documentation, you can pass:

queryset.prefetch_related(None)

As it will clear any prefetch_related behavior

Here is the reference for it Click Here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM