From eee3db88200755c713b1412ae133f768dbcd96e9 Mon Sep 17 00:00:00 2001 From: Phillip Shiu Date: Thu, 22 Jun 2023 22:42:49 -0400 Subject: [PATCH] perf: run `select count(*)` only once for entitlements.count() Not much of an optimization, but might shave a couple seconds if the number of entitlements on production are large. Django will use the _result_cache if the QuerySet has already been retrieved: https://github.com/django/django/blob/107865780aa44914e21d27fdf4ca269bc61c7f01/django/db/models/query.py#L597-L598 --- .../management/commands/expire_and_create_entitlements.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/common/djangoapps/entitlements/management/commands/expire_and_create_entitlements.py b/common/djangoapps/entitlements/management/commands/expire_and_create_entitlements.py index 9e690423b3..da81ce357a 100644 --- a/common/djangoapps/entitlements/management/commands/expire_and_create_entitlements.py +++ b/common/djangoapps/entitlements/management/commands/expire_and_create_entitlements.py @@ -85,7 +85,8 @@ class Command(BaseCommand): enrollment_course_run__isnull=True, course_uuid__in=exceptional_courses) entitlements = normal_entitlements | exceptional_entitlements - logger.info('Total entitlements that have reached expiration period are %d ', entitlements.count()) + entitlements_count = entitlements.count() + logger.info('Total entitlements that have reached expiration period are %d ', entitlements_count) entitlements_to_expire = max(1, options.get('count')) batch_size = max(1, options.get('batch_size')) @@ -102,7 +103,7 @@ class Command(BaseCommand): for batch_num in range(num_batches): start = batch_num * batch_size - end = min(start + batch_size, entitlements_to_expire, entitlements.count()) + end = min(start + batch_size, entitlements_to_expire, entitlements_count) expire_and_create_entitlements.delay(entitlements[start:end], support_user) logger.info('Done. Successfully enqueued %d tasks.', num_batches)