From 01c28a4d629804c44f2d60cc80eafd83d23695c5 Mon Sep 17 00:00:00 2001 From: DavidVadnais Date: Wed, 19 Mar 2025 23:09:54 +0000 Subject: [PATCH] faster query for followup_date --- helpdesk/query.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/helpdesk/query.py b/helpdesk/query.py index 7e1eb77b..ea69a133 100644 --- a/helpdesk/query.py +++ b/helpdesk/query.py @@ -1,6 +1,8 @@ from base64 import b64decode, b64encode from django.db.models import Q, Max +from django.db.models import F, Window, Subquery, OuterRef +from .models import FollowUp from django.urls import reverse from django.utils.html import escape from django.utils.translation import gettext as _ @@ -175,8 +177,21 @@ class __Query__: # django orm '-' -> desc if order == 'desc': order_column = '-' + order_column - - queryset = objects.annotate(last_followup=Max('followup__date')).order_by(order_by) + + queryset = objects.annotate( + last_followup=Subquery( + FollowUp.objects.order_by().annotate( + last_followup=Window( + expression=Max("date"), + partition_by=[F("ticket_id"),], + order_by="-date" + ) + ).filter( + ticket_id=OuterRef("id") + ).values("last_followup").distinct() + ) + ).order_by(order_by) + total = queryset.count() if search_value: # Dead code currently