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

4๐Ÿ‘

โœ…

I prefer to add these Prefetch related clauses in a custom QuerySet and then access the created lists through model properties, if they 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') and len(self.comments_list) > 0:
            return self.comments_list[0]
        return None
๐Ÿ‘คMark Galloway

Leave a comment