diff --git a/ami/main/migrations/0084_index_detection_occurrence_timestamp.py b/ami/main/migrations/0084_index_detection_occurrence_timestamp.py new file mode 100644 index 000000000..b46b980ac --- /dev/null +++ b/ami/main/migrations/0084_index_detection_occurrence_timestamp.py @@ -0,0 +1,21 @@ +from django.contrib.postgres.operations import AddIndexConcurrently +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("main", "0083_dedupe_taxalist_names"), + ] + + # AddIndexConcurrently requires running outside a transaction. + atomic = False + + operations = [ + AddIndexConcurrently( + model_name="detection", + index=models.Index( + fields=["occurrence", "-timestamp"], + name="detection_occurrence_ts_desc", + ), + ), + ] diff --git a/ami/main/models.py b/ami/main/models.py index c604c6319..2859f95d2 100644 --- a/ami/main/models.py +++ b/ami/main/models.py @@ -2778,6 +2778,16 @@ class Meta: "frame_num", "timestamp", ] + indexes = [ + # Supports /captures/ list ordering and joins from Occurrence to + # its detections by (occurrence_id, timestamp DESC). Django's FK + # index alone is on occurrence_id, which forces a sort on a large + # row set after the join. + models.Index( + fields=["occurrence", "-timestamp"], + name="detection_occurrence_ts_desc", + ), + ] def best_classification(self): # @TODO where is this used?