From 83f9fa74f0b1316f1faf207301ae8048010f397d Mon Sep 17 00:00:00 2001 From: Mark Jones Date: Tue, 12 Jul 2022 02:08:11 +0200 Subject: [PATCH] Fixes #854 I don't think this is perfect but I haven't dug in deep enough to know what would be. --- django_tables2/columns/base.py | 7 ++++++- django_tables2/data.py | 13 +++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/django_tables2/columns/base.py b/django_tables2/columns/base.py index 75a04ae0..82dca180 100644 --- a/django_tables2/columns/base.py +++ b/django_tables2/columns/base.py @@ -397,7 +397,12 @@ def order(self, queryset, is_descending): returns: Tuple (QuerySet, boolean) """ - return (queryset, False) + from django.db.models import F, OrderBy + + if self.order_by or self.accessor: # TODO: self.orderable + return queryset, OrderBy(F(self.order_by or self.accessor), descending=is_descending) + + return queryset, None @classmethod def from_field(cls, field, **kwargs): diff --git a/django_tables2/data.py b/django_tables2/data.py index be909c49..4a533b9b 100644 --- a/django_tables2/data.py +++ b/django_tables2/data.py @@ -197,8 +197,8 @@ def order_by(self, aliases): columns ('-' indicates descending order) in order of significance with regard to data ordering. """ - modified_any = False accessors = [] + orderables = tuple() for alias in aliases: bound_column = self.table.columns[OrderBy(alias).bare] # bound_column.order_by reflects the current ordering applied to @@ -210,14 +210,15 @@ def order_by(self, aliases): accessors += bound_column.order_by if bound_column: - queryset, modified = bound_column.order(self.data, alias[0] == "-") + # We have to pass queryset because ordering could be on an annotation that was + # added for sorting + self.data, ordering = bound_column.order(self.data, alias[0] == "-") - if modified: - self.data = queryset - modified_any = True + orderables = orderables + (ordering,) # custom ordering - if modified_any: + if orderables: + self.data = self.data.order_by(*orderables) return # Traditional ordering