I have a page view in Django set up as follows:
blog = get_object_or_404(Blog, subdomain=extracted.subdomain)
all_posts = Post.objects.filter(
blog=blog, publish=True).order_by('-published_date')
nav = all_posts.filter(is_page=True)
posts = all_posts.filter(is_page=False)
This causes the DB to be accessed 3 times. I'm trying to optimize this to only access the DB once. The following snippet reduces the number of calls to 2, but I'm sure there is a better way than this that I don't know about.
blog = get_object_or_404(Blog, subdomain=extracted.subdomain)
all_posts = Post.objects.filter(
blog=blog, publish=True).order_by('-published_date')
nav = []
posts = []
for post in all_posts:
if post.is_page:
nav.append(post)
else:
posts.append(post)
As far as I understand, prefetch_related and select_related work inversely and I'm unsure how to implement them in this context.
My models are set up as follows:
class Blog(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
title = models.CharField(max_length=200)
...
class Post(models.Model):
blog = models.ForeignKey(
Blog,
on_delete=models.CASCADE,
related_name='post')
title = models.CharField(max_length=200)
...
Thanks in advance!
Edit:
And for some reason this executes 3 DB requests
blog = get_object_or_404(Blog.objects.prefetch_related('post_set'), subdomain=extracted.subdomain)
posts = blog.post_set.filter(publish=True).order_by('-published_date')
is_pagewhen rendering. Only on the first iteration will the queryset be evaluated.