From 2f1f95fea91551c09be2b2771afbdcd3caf6b852 Mon Sep 17 00:00:00 2001 From: Tom Hacohen Date: Sun, 19 Jun 2022 22:25:49 +0300 Subject: [PATCH] Optimize how we fetch the latest (current) revision The way were were doing it was implicitly sorting the query items and it was causing millions of items to be sorted (even though the result should only have one) making it slow. By switching away from `get()` and `first()` we are telling django to not try to sort. --- etebase_server/django/models.py | 2 +- etebase_server/fastapi/routers/collection.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/etebase_server/django/models.py b/etebase_server/django/models.py index 4640e6d..e3a8e7f 100644 --- a/etebase_server/django/models.py +++ b/etebase_server/django/models.py @@ -96,7 +96,7 @@ class CollectionItem(models.Model): @cached_property def content(self) -> "CollectionItemRevision": - return self.revisions.get(current=True) + return self.revisions.filter(current=True)[0] @property def etag(self) -> str: diff --git a/etebase_server/fastapi/routers/collection.py b/etebase_server/fastapi/routers/collection.py index 6722c78..c847743 100644 --- a/etebase_server/fastapi/routers/collection.py +++ b/etebase_server/fastapi/routers/collection.py @@ -396,7 +396,7 @@ def item_create(item_model: CollectionItemIn, collection: models.Collection, val if not created: # We don't have to use select_for_update here because the unique constraint on current guards against # the race condition. But it's a good idea because it'll lock and wait rather than fail. - current_revision = instance.revisions.filter(current=True).select_for_update().first() + current_revision = instance.revisions.filter(current=True).select_for_update()[0] assert current_revision is not None current_revision.current = None current_revision.save()