Skip to content

Commit e9e44ed

Browse files
committed
feat: move common queries to a model queryset
1 parent 0925856 commit e9e44ed

File tree

2 files changed

+26
-9
lines changed

2 files changed

+26
-9
lines changed

ami/main/api/views.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -861,12 +861,8 @@ def get_queryset(self) -> QuerySet:
861861
"determination",
862862
"deployment",
863863
"event",
864-
).annotate(
865-
detections_count=models.Count("detections", distinct=True),
866-
duration=models.Max("detections__timestamp") - models.Min("detections__timestamp"),
867-
first_appearance_timestamp=models.Min("detections__timestamp"),
868-
first_appearance_time=models.Min("detections__timestamp__time"),
869864
)
865+
qs = qs.with_detections_count().with_timestamps() # type: ignore
870866
if self.action == "list":
871867
qs = (
872868
qs.all()

ami/main/models.py

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1933,11 +1933,32 @@ def __str__(self) -> str:
19331933
return f"#{self.pk} from SourceImage #{self.source_image_id} with Algorithm #{self.detection_algorithm_id}"
19341934

19351935

1936-
@final
1936+
class OccurrenceQuerySet(models.QuerySet):
1937+
def with_detections_count(self) -> models.QuerySet:
1938+
return self.annotate(detections_count=models.Count("detections", distinct=True))
1939+
1940+
def with_timestamps(self) -> models.QuerySet:
1941+
"""
1942+
These are timestamps used for filtering and ordering in the UI.
1943+
"""
1944+
return self.annotate(
1945+
first_appearance_timestamp=models.Min("detections__timestamp"),
1946+
last_appearance_timestamp=models.Max("detections__timestamp"),
1947+
first_appearance_time=models.Min("detections__timestamp__time"),
1948+
duration=models.ExpressionWrapper(
1949+
models.F("last_appearance_timestamp") - models.F("first_appearance_timestamp"),
1950+
output_field=models.DurationField(),
1951+
),
1952+
)
1953+
1954+
19371955
class OccurrenceManager(models.Manager):
1938-
def get_queryset(self):
1939-
# prefetch determination, deployment, project
1940-
return super().get_queryset().select_related("determination", "deployment", "project")
1956+
def get_queryset(self) -> OccurrenceQuerySet:
1957+
return OccurrenceQuerySet(self.model, using=self._db).select_related(
1958+
"determination",
1959+
"deployment",
1960+
"project",
1961+
)
19411962

19421963

19431964
@final

0 commit comments

Comments
 (0)