From 026fba867dd6b8862be4519e8d9e7a2c54764106 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Delobelle?= Date: Thu, 6 Apr 2017 19:44:16 +0200 Subject: [PATCH] Fewer db requests on home view. - 1 request instead of (2 + #articles) --- kfet/views.py | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/kfet/views.py b/kfet/views.py index 6d8af17d..db13f403 100644 --- a/kfet/views.py +++ b/kfet/views.py @@ -55,11 +55,21 @@ class Home(TemplateView): template_name = "kfet/home.html" def get_context_data(self, **kwargs): - context = super(TemplateView, self).get_context_data(**kwargs) - articles = Article.objects.all().filter(is_sold=True, hidden=False) - context['pressions'] = articles.filter(category__name='Pression') - context['articles'] = (articles.exclude(category__name='Pression') - .order_by('category')) + context = super().get_context_data(**kwargs) + articles = list( + Article.objects + .filter(is_sold=True, hidden=False) + .select_related('category') + .order_by('category__name') + ) + pressions, others = [], [] + while len(articles) > 0: + article = articles.pop() + if article.category.name == 'Pression': + pressions.append(article) + else: + others.append(article) + context['pressions'], context['articles'] = pressions, others return context @method_decorator(login_required)