From 6988b225c946c86db7e24507424a2b3fd8dba39a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20P=C3=A9ters?= Date: Tue, 24 Dec 2019 10:14:55 +0100 Subject: [PATCH] manager: reduce number of queries when listing events (#38699) --- chrono/agendas/models.py | 38 ++++++++++++++++++- .../manager_events_agenda_month_view.html | 10 ++--- .../manager_events_agenda_settings.html | 12 +++--- chrono/manager/views.py | 9 +++++ tests/test_agendas.py | 27 +++++++++++++ 5 files changed, 84 insertions(+), 12 deletions(-) diff --git a/chrono/agendas/models.py b/chrono/agendas/models.py index e4e85007..50ec863b 100644 --- a/chrono/agendas/models.py +++ b/chrono/agendas/models.py @@ -20,11 +20,12 @@ import math import requests import vobject +import django from django.conf import settings from django.contrib.auth.models import Group from django.core.exceptions import ValidationError from django.db import models, transaction -from django.db.models import Q +from django.db.models import Count, Q, Case, When from django.urls import reverse from django.utils.dates import WEEKDAYS from django.utils.encoding import force_text @@ -358,6 +359,41 @@ class Event(models.Model): return False return True + @staticmethod + def annotate_queryset(qs): + if django.VERSION < (2, 0): + return qs.annotate( + booked_places_count=Count( + Case( + When( + booking__cancellation_datetime__isnull=True, + booking__in_waiting_list=False, + then='booking', + ) + ) + ), + waiting_list_count=Count( + Case( + When( + booking__cancellation_datetime__isnull=True, + booking__in_waiting_list=True, + then='booking', + ) + ) + ), + ) + else: + return qs.annotate( + booked_places_count=Count( + 'booking', + filter=Q(booking__cancellation_datetime__isnull=True, booking__in_waiting_list=False), + ), + waiting_list_count=Count( + 'booking', + filter=Q(booking__cancellation_datetime__isnull=True, booking__in_waiting_list=True), + ), + ) + @property def booked_places(self): return self.booking_set.filter(cancellation_datetime__isnull=True, in_waiting_list=False).count() diff --git a/chrono/manager/templates/chrono/manager_events_agenda_month_view.html b/chrono/manager/templates/chrono/manager_events_agenda_month_view.html index a64e7ad4..f419a937 100644 --- a/chrono/manager/templates/chrono/manager_events_agenda_month_view.html +++ b/chrono/manager/templates/chrono/manager_events_agenda_month_view.html @@ -8,13 +8,13 @@ {% if object_list %}