mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-08-13 22:33:19 +00:00
Add helpers for versioning by version_index
This commit is contained in:
@@ -5,12 +5,34 @@ from enum import StrEnum
|
||||
from typing import TYPE_CHECKING
|
||||
from typing import Any
|
||||
|
||||
from django.db.models import F
|
||||
from django.db.models import QuerySet
|
||||
|
||||
from documents.models import Document
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from rest_framework.request import Request
|
||||
|
||||
|
||||
def versions_newest_first(documents: QuerySet[Document]) -> QuerySet[Document]:
|
||||
"""
|
||||
Sorts versions so the newest one comes first using version_index and not on id,
|
||||
because an existing document can be merged in as a version
|
||||
"""
|
||||
return documents.order_by(F("version_index").desc(nulls_last=True), "-id")
|
||||
|
||||
|
||||
def sort_versions_newest_first(documents: list[Document]) -> list[Document]:
|
||||
"""
|
||||
Same sorting as versions_newest_first()
|
||||
"""
|
||||
return sorted(
|
||||
documents,
|
||||
key=lambda doc: (doc.version_index or 0, doc.id),
|
||||
reverse=True,
|
||||
)
|
||||
|
||||
|
||||
class VersionResolutionError(StrEnum):
|
||||
INVALID = "invalid"
|
||||
NOT_FOUND = "not_found"
|
||||
@@ -51,7 +73,7 @@ def get_latest_version_for_root(
|
||||
include_deleted: bool = False,
|
||||
) -> Document:
|
||||
manager = _document_manager(include_deleted=include_deleted)
|
||||
latest = manager.filter(root_document=root_doc).order_by("-id").first()
|
||||
latest = versions_newest_first(manager.filter(root_document=root_doc)).first()
|
||||
return latest or root_doc
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user