|
46 | 46 |
|
47 | 47 | from django.contrib.postgres.aggregates import ArrayAgg |
48 | 48 | from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured |
49 | | -from django.db.models import Case, F, Max, Q, When |
| 49 | +from django.db.models import F, Q, OuterRef, Subquery |
50 | 50 | from django.db.models.functions import Coalesce |
51 | 51 |
|
52 | 52 | from django_smartbase_admin.plugins.base import SBAdminPlugin |
@@ -384,13 +384,18 @@ def _build_grouped_qs( |
384 | 384 | # yields that parent's value — the group sorts by the |
385 | 385 | # parent, not by any of its children. |
386 | 386 | parent_row = Q(**{f"{parent_field}__isnull": True}) |
| 387 | + column_fields_map = {cf.field: cf for cf in action.column_fields} |
387 | 388 | sort_annotations: dict = {} |
388 | 389 | new_order: list[str] = [] |
389 | 390 | for idx, expr in enumerate(order_strings): |
390 | 391 | desc = expr.startswith("-") |
391 | 392 | field = expr.lstrip("-+") |
392 | 393 | alias = f"_nested_sort_{idx}" |
393 | | - sort_annotations[alias] = Max(Case(When(parent_row, then=F(field)))) |
| 394 | + visible_field = column_fields_map.get(field) |
| 395 | + sort_parent_qs = action.get_data_queryset(visible_fields=[visible_field] if visible_field else []) |
| 396 | + sort_annotations[alias] = Subquery( |
| 397 | + sort_parent_qs.filter(id=OuterRef("parent_real_id")).values(field)[:1] |
| 398 | + ) |
394 | 399 | new_order.append(f"-{alias}" if desc else alias) |
395 | 400 | return grouped.annotate(**sort_annotations).order_by(*new_order) |
396 | 401 |
|
|
0 commit comments