From 11a06901ad7a03f77762690aa8659e227b509496 Mon Sep 17 00:00:00 2001 From: Omar Al-Ithawi Date: Wed, 12 Oct 2022 11:14:33 +0300 Subject: [PATCH] faster total_site_certificates_as_of_date avoid pulling thousands of certificates just for count using .first() to utilize SQL LIMIT 1 : https://github.com/django/django/blob/2a62cdcfec85938f40abb2e9e6a9ff497e02afe8/django/db/models/query.py#L651-L654 Debugging doc: https://appsembler.atlassian.net/wiki/spaces/RT/pages/2680783079/RED-3513+-+Debug+slow+response+times#Figures-slow-query --- figures/metrics.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/figures/metrics.py b/figures/metrics.py index d380d11a..77a7a32e 100644 --- a/figures/metrics.py +++ b/figures/metrics.py @@ -413,11 +413,11 @@ def total_site_certificates_as_of_date(site, date_for): return data['num_learners_completed__sum'] ``` """ - qs = CourseDailyMetrics.objects.filter( + latest_daily_metrics = CourseDailyMetrics.objects.filter( site=site, - date_for__lte=date_for).order_by('-date_for') - if qs: - latest_date = qs[0].date_for + date_for__lte=date_for).order_by('-date_for').first() + if latest_daily_metrics: + latest_date = latest_daily_metrics.date_for recs = CourseDailyMetrics.objects.filter(site=site, date_for=latest_date) data = recs.aggregate(Sum('num_learners_completed'))