Skip to content

Commit ade5cb6

Browse files
authored
Allow Column.sortable=True override. This allows you to turn on sorting for annotated columns. (iommirocks#702)
1 parent 6203d84 commit ade5cb6

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

iommi/table.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,10 @@ def default_cell__value(column, row, **kwargs):
324324
return None
325325

326326

327+
def default_sortable(column, **_):
328+
return column.attr is not None
329+
330+
327331
class DataRetrievalMethods(Enum):
328332
attribute_access = auto()
329333
prefetch = auto()
@@ -405,7 +409,7 @@ class Meta:
405409
@with_defaults(
406410
attr=MISSING,
407411
sort_default_desc=False,
408-
sortable=lambda column, **_: column.attr is not None,
412+
sortable=default_sortable,
409413
auto_rowspan=False,
410414
bulk__include=False,
411415
data_retrieval_method=DataRetrievalMethods.attribute_access,
@@ -510,7 +514,7 @@ def on_bind(self) -> None:
510514
# Not strict evaluate on purpose
511515
self.model = evaluate(self.model, **self.iommi_evaluate_parameters())
512516

513-
if self.table.model and self.attr is not None and self.sortable:
517+
if self.table.model and self.attr is not None and (self.iommi_namespace['sortable'] is MISSING or self.iommi_namespace['sortable'] is default_sortable):
514518
if '__' not in self.attr:
515519
# Only validate one level of the path for now
516520
try:

iommi/table__tests.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from django.db.models import (
1313
F,
1414
QuerySet,
15+
Sum,
1516
)
1617
from django.http import HttpResponse
1718
from django.test import override_settings
@@ -4736,6 +4737,23 @@ def preprocess_rows(rows, **_):
47364737
assert not t.columns.synthetic.sortable
47374738

47384739

4740+
@pytest.mark.django_db
4741+
def test_allow_sorting_on_annotated_column():
4742+
T1.objects.create(pk=1, foo='a', bar='b')
4743+
4744+
t = Table(
4745+
auto__rows=T1.objects.all().annotate(annotated=Sum('pk')),
4746+
columns__annotated=Column(
4747+
sortable=True,
4748+
),
4749+
)
4750+
4751+
# This should not crash
4752+
t = t.bind(request=req('get', **{'order': 'annotated'}))
4753+
4754+
assert t.columns.annotated.sortable
4755+
4756+
47394757
@pytest.mark.skip('Validation is only done on the first level, not on nested levels for now')
47404758
@pytest.mark.django_db
47414759
def test_disallow_sorting_on_non_sortable_columns_that_have_valid_attr__nested():

0 commit comments

Comments
 (0)