Django: Save multiple Prefetch() objects in a variable or method -


the documentation displays how save prefetch() object in variable:

>>> prefetch = prefetch('choice_set', queryset=voted_choices, to_attr='voted_choices') >>> question.objects.prefetch_related(prefetch).get().voted_choices [<choice: sky>] 

however, prefetch_related accepts many prefetch() objects separated comma:

>>> question.objects.prefetch_related(prefetch('choice_set'), prefetch('foo')).get().voted_choices 

how prefetch() sequence saved in variable -or better in method- in order reusable?

i prefer add these prefetch related clauses in custom queryset , access created lists through model properties, if exist.

usage: 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') , len(self.comments_list) > 0:             return self.comments_list[0]         return none 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -