Skip to content

Commit

Permalink
Move the post prefetch into an earlier call to reduce sql queries
Browse files Browse the repository at this point in the history
  • Loading branch information
stuartmaxwell committed Oct 21, 2024
1 parent c9100b9 commit 7903987
Showing 1 changed file with 7 additions and 8 deletions.
15 changes: 7 additions & 8 deletions src/djpress/models/post.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,9 +158,10 @@ def get_published_posts(self: "PostsManager") -> models.QuerySet:
- The status must be "published".
- The date must be less than or equal to the current date/time.
"""
return self.get_queryset().filter(
status="published",
date__lte=timezone.now(),
return (
self.get_queryset()
.filter(status="published", date__lte=timezone.now())
.prefetch_related("categories", "author")
)

def get_recent_published_posts(self: "PostsManager") -> models.QuerySet:
Expand All @@ -174,9 +175,7 @@ def get_recent_published_posts(self: "PostsManager") -> models.QuerySet:
if djpress_settings.CACHE_RECENT_PUBLISHED_POSTS:
return self._get_cached_recent_published_posts()

return self.get_published_posts().prefetch_related("categories", "author")[
: djpress_settings.RECENT_PUBLISHED_POSTS_COUNT
]
return self.get_published_posts()[: djpress_settings.RECENT_PUBLISHED_POSTS_COUNT]

def _get_cached_recent_published_posts(self: "PostsManager") -> models.QuerySet:
"""Return the cached recent published posts queryset.
Expand Down Expand Up @@ -275,7 +274,7 @@ def get_published_posts_by_category(
Must have a date less than or equal to the current date/time for a specific
category, ordered by date in descending order.
"""
return self.get_published_posts().filter(categories=category).prefetch_related("categories", "author")
return self.get_published_posts().filter(categories=category)

def get_published_posts_by_author(
self: "PostsManager",
Expand All @@ -286,7 +285,7 @@ def get_published_posts_by_author(
Must have a date less than or equal to the current date/time for a specific
author, ordered by date in descending order.
"""
return self.get_published_posts().filter(author=author).prefetch_related("categories", "author")
return self.get_published_posts().filter(author=author)


class Post(models.Model):
Expand Down

0 comments on commit 7903987

Please sign in to comment.