From 11f65ff7aac899d713c158c38771b347bb0d3b34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C4=93teris=20Caune?= Date: Wed, 12 Dec 2018 19:04:37 +0200 Subject: [PATCH] Optimize db query in `sendalerts` --- hc/api/management/commands/sendalerts.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/hc/api/management/commands/sendalerts.py b/hc/api/management/commands/sendalerts.py index 1adf87f1..431d0357 100644 --- a/hc/api/management/commands/sendalerts.py +++ b/hc/api/management/commands/sendalerts.py @@ -82,7 +82,12 @@ class Command(BaseCommand): now = timezone.now() - check = Check.objects.filter(alert_after__lt=now, status="up").first() + # In PostgreSQL, add this index to run the below query efficiently: + # CREATE INDEX api_check_up ON api_check (alert_after) WHERE status = 'up' + + q = Check.objects.filter(alert_after__lt=now, status="up") + # Sort by alert_after, to avoid unnecessary sorting by id: + check = q.order_by("alert_after").first() if check is None: return False