Send ordered document list to Django REST pagination

Currently, when pages of documents are requested from the API, the
webserver logs a warning:

```
gunicorn[1550]: /home/madduck/code/paperless-ngx/.direnv/python-3.11.2/lib/python3.11/site-packages/rest_framework/pagination.py:200: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'documents.models.Document'> QuerySet.
```

This can yield unexpected and problematic results, including duplicate
and missing IDs in the enumeration, as demonstrated in
https://github.com/paperless-ngx/paperless-ngx/discussions/6859

The patch is simple: turn the unordered Documents QuerySet into
one that's ordered by reverse creation date, which is the default
ordering for `Document`.

Note that the default ordering for `Document` means that
`QuerySet.ordered` is actually `True` following the call to
`distinct()`, but after `annotate()`, the flag changes to `False`,
unless `order_by()` is used explicitly, as per this patch.

Closes: https://github.com/paperless-ngx/paperless-ngx/discussions/6859

Signed-off-by: martin f. krafft <madduck@madduck.net>
This commit is contained in:
martin f. krafft 2024-06-12 11:46:05 +02:00
parent 9e8b96cd34
commit dd7a192da8

View File

@ -364,6 +364,7 @@ class DocumentViewSet(
def get_queryset(self):
return (
Document.objects.distinct()
.order_by("-created")
.annotate(num_notes=Count("notes"))
.select_related("correspondent", "storage_path", "document_type", "owner")
.prefetch_related("tags", "custom_fields", "notes")