pre-fetch versions

This commit is contained in:
shamoon
2026-02-12 11:10:41 -08:00
parent 3b4112f930
commit c7c9845806
2 changed files with 34 additions and 7 deletions

View File

@@ -1145,13 +1145,25 @@ class DocumentSerializer(
root_doc = obj if obj.root_document_id is None else obj.root_document
if root_doc is None:
return []
versions_qs = Document.objects.filter(root_document=root_doc).only(
"id",
"added",
"checksum",
"version_label",
prefetched_cache = getattr(obj, "_prefetched_objects_cache", None)
prefetched_versions = (
prefetched_cache.get("versions")
if isinstance(prefetched_cache, dict)
else None
)
versions = [*versions_qs, root_doc]
versions: list[Document]
if prefetched_versions is not None:
versions = [*prefetched_versions, root_doc]
else:
versions_qs = Document.objects.filter(root_document=root_doc).only(
"id",
"added",
"checksum",
"version_label",
)
versions = [*versions_qs, root_doc]
def build_info(doc: Document) -> _DocumentVersionInfo:
return {

View File

@@ -35,6 +35,7 @@ from django.db.models import IntegerField
from django.db.models import Max
from django.db.models import Model
from django.db.models import OuterRef
from django.db.models import Prefetch
from django.db.models import Q
from django.db.models import Subquery
from django.db.models import Sum
@@ -797,7 +798,21 @@ class DocumentViewSet(
.annotate(effective_content=Coalesce(latest_version_content, F("content")))
.annotate(num_notes=Count("notes"))
.select_related("correspondent", "storage_path", "document_type", "owner")
.prefetch_related("tags", "custom_fields", "notes")
.prefetch_related(
Prefetch(
"versions",
queryset=Document.objects.only(
"id",
"added",
"checksum",
"version_label",
"root_document_id",
),
),
"tags",
"custom_fields",
"notes",
)
)
def get_serializer(self, *args, **kwargs):