[Answered ]-Need Django Query optimization (2 Queries instead of 21)

1👍

Try to combine the querysets using OR | operator:

def home(self) -> QuerySet:
    articles_pks = Article.objects.none()
    for ws in WebSite.objects.active().order_by('home_order', 'name'):
        articles_pks = articles_pks | ws.articles.filter(is_active=True).order_by('-created')[:ws.home_article_count]
    return self.get_queryset().filter(pk__in=articles_pks.values_list('pk',flat=True)))

You should end up with just two queries, one to get the websites and one for building and using the article list.

Leave a comment