Skip to content

A community-supported supercharged document management system: scan, index and archive all your documents

Fixes an N+1 query in matching with the version content fetching by prefetching versions (#12562)

Trenton H8c1225e120ca
diff --git a/src/documents/consumer.py b/src/documents/consumer.py
index 8035f3857..6656a3d96 100644
--- a/src/documents/consumer.py
+++ b/src/documents/consumer.py
@@ -650,6 +650,10 @@ class ConsumerPlugin(
# If we get here, it was successful. Proceed with post-consume
# hooks. If they fail, nothing will get changed.
+ document = Document.objects.prefetch_related("versions").get(
+ pk=document.pk,
+ )
+
document_consumption_finished.send(
sender=self.__class__,
document=document,
diff --git a/src/documents/models.py b/src/documents/models.py
index 9af5fbc23..e2f5bb3dc 100644
--- a/src/documents/models.py
+++ b/src/documents/models.py
@@ -381,7 +381,10 @@ class Document(SoftDeleteModel, ModelWithOwner): # type: ignore[django-manager-
if isinstance(prefetched_cache, dict)
else None
)
- if prefetched_versions:
+ if prefetched_versions is not None:
+ # Empty list means prefetch ran and found no versions — use own content.
+ if not prefetched_versions:
+ return self.content
latest_prefetched = max(prefetched_versions, key=lambda doc: doc.id)
return latest_prefetched.content
diff --git a/src/documents/views.py b/src/documents/views.py
index dd9c4b837..8d86aa776 100644
--- a/src/documents/views.py
+++ b/src/documents/views.py
@@ -1248,7 +1248,10 @@ class DocumentViewSet(
),
)
def suggestions(self, request, pk=None):
- doc = get_object_or_404(Document.objects.select_related("owner"), pk=pk)
+ doc = get_object_or_404(
+ Document.objects.select_related("owner").prefetch_related("versions"),
+ pk=pk,
+ )
if request.user is not None and not has_perms_owner_aware(
request.user,
"view_document",