mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2025-04-29 11:09:27 -05:00
Handle distinct issue
This commit is contained in:
parent
4d2e211ec1
commit
590c638ba0
@ -911,24 +911,35 @@ class DocumentsOrderingFilter(OrderingFilter):
|
|||||||
if not annotation:
|
if not annotation:
|
||||||
raise ValueError("Invalid custom field data type")
|
raise ValueError("Invalid custom field data type")
|
||||||
|
|
||||||
queryset = queryset.annotate(
|
ids_sorted_by_cf = (
|
||||||
# We need to annotate the queryset with the custom field value
|
queryset.annotate(
|
||||||
custom_field_value=annotation,
|
# We need to annotate the queryset with the custom field value
|
||||||
# We also need to annotate the queryset with a boolean for sorting whether the field exists
|
custom_field_value=annotation,
|
||||||
has_field=Exists(
|
# We also need to annotate the queryset with a boolean for sorting whether the field exists
|
||||||
CustomFieldInstance.objects.filter(
|
has_field=Exists(
|
||||||
document_id=OuterRef("id"),
|
CustomFieldInstance.objects.filter(
|
||||||
field_id=custom_field_id,
|
document_id=OuterRef("id"),
|
||||||
|
field_id=custom_field_id,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
)
|
||||||
|
.order_by(
|
||||||
|
"-has_field",
|
||||||
|
param.replace(
|
||||||
|
self.prefix + str(custom_field_id),
|
||||||
|
"custom_field_value",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.values_list("id", flat=True)
|
||||||
)
|
)
|
||||||
|
|
||||||
queryset = queryset.order_by(
|
# We need to preserve the order of the ids sorted by custom field, see https://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct
|
||||||
"-has_field",
|
preserved = Case(
|
||||||
param.replace(
|
*[
|
||||||
self.prefix + str(custom_field_id),
|
When(id=id, then=position)
|
||||||
"custom_field_value",
|
for position, id in enumerate(ids_sorted_by_cf)
|
||||||
),
|
],
|
||||||
)
|
)
|
||||||
|
queryset = queryset.filter(id__in=ids_sorted_by_cf).order_by(preserved)
|
||||||
|
|
||||||
return super().filter_queryset(request, queryset, view)
|
return super().filter_queryset(request, queryset, view)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user