From 24359e33f0d92d735c15f3e13bdbabe942de3d94 Mon Sep 17 00:00:00 2001 From: Scott Gigante Date: Sat, 9 Dec 2023 13:47:24 -0500 Subject: [PATCH] adds `get_ordering` method to GenericAPIView following the pattern of e.g. `django.contrib.admin.ModelAdmin.get_fieldsets`, this PR adds an overrideable accessor to get `viewset.ordering` in order to enable dynamic default orderings. An example of where this is useful is in the case of a SearchFilter which returns results ranked based on similarity, in which case the default ordering should be ignored/bypassed. --- rest_framework/filters.py | 6 +++--- rest_framework/generics.py | 9 +++++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/rest_framework/filters.py b/rest_framework/filters.py index 065e72f94a7..05073c86eff 100644 --- a/rest_framework/filters.py +++ b/rest_framework/filters.py @@ -242,10 +242,10 @@ def get_ordering(self, request, queryset, view): return ordering # No ordering was included, or all the ordering fields were invalid - return self.get_default_ordering(view) + return self.get_default_ordering(request, queryset, view) - def get_default_ordering(self, view): - ordering = getattr(view, 'ordering', None) + def get_default_ordering(self, request, queryset, view): + ordering = view.get_ordering(request, queryset) if isinstance(ordering, str): return (ordering,) return ordering diff --git a/rest_framework/generics.py b/rest_framework/generics.py index 1673033214a..2290d3ce963 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -104,6 +104,15 @@ def get_object(self): return obj + def get_ordering(self, request, queryset): + """ + Returns the default ordering defined on the view. + + You may want to override this if you wish the default ordering to be dependent + on the request. + """ + return getattr(self, "ordering", None) + def get_serializer(self, *args, **kwargs): """ Return the serializer instance that should be used for validating and