From fa66851889c1f56de9f9e66278ab5580c28248f2 Mon Sep 17 00:00:00 2001 From: imperosol Date: Sat, 21 Dec 2024 21:03:52 +0100 Subject: [PATCH] fix n+1 queries on birthdays --- com/templates/com/news_list.jinja | 33 ++++++++++++++----------------- com/views.py | 7 ++++--- 2 files changed, 19 insertions(+), 21 deletions(-) diff --git a/com/templates/com/news_list.jinja b/com/templates/com/news_list.jinja index bcb0eb6e..ac9a7892 100644 --- a/com/templates/com/news_list.jinja +++ b/com/templates/com/news_list.jinja @@ -136,25 +136,22 @@ type="EVENT").order_by('dates__start_date') %}
{% trans %}Birthdays{% endtrans %}
- {% if user.is_subscribed %} - {# Cache request for 1 hour #} - {% cache 3600 "birthdays" %} -
    - {% for d in birthdays.dates('date_of_birth', 'year', 'DESC') %} -
  • - {% trans age=timezone.now().year - d.year %}{{ age }} year old{% endtrans %} - -
  • - {% endfor %} -
- {% endcache %} - {% else %} + {%- if user.is_subscribed -%} +
    + {%- for year, users in birthdays -%} +
  • + {% trans age=timezone.now().year - year %}{{ age }} year old{% endtrans %} + +
  • + {%- endfor -%} +
+ {%- else -%}

{% trans %}You need an up to date subscription to access this content{% endtrans %}

- {% endif %} + {%- endif -%}
diff --git a/com/views.py b/com/views.py index d4136d20..1b7ab8bc 100644 --- a/com/views.py +++ b/com/views.py @@ -21,7 +21,7 @@ # Place - Suite 330, Boston, MA 02111-1307, USA. # # - +import itertools from datetime import timedelta from smtplib import SMTPRecipientsRefused @@ -374,13 +374,14 @@ class NewsListView(CanViewMixin, ListView): kwargs = super().get_context_data(**kwargs) kwargs["NewsDate"] = NewsDate kwargs["timedelta"] = timedelta - kwargs["birthdays"] = ( + kwargs["birthdays"] = itertools.groupby( User.objects.filter( date_of_birth__month=localdate().month, date_of_birth__day=localdate().day, ) .filter(role__in=["STUDENT", "FORMER STUDENT"]) - .order_by("-date_of_birth") + .order_by("-date_of_birth"), + key=lambda u: u.date_of_birth.year, ) return kwargs