Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move the post prefetch into an earlier call to reduce sql queries #32

Merged
merged 1 commit into from
Oct 21, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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