Skip to content

Commit

Permalink
adds get_ordering method to GenericAPIView
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
scottgigante committed Dec 9, 2023
1 parent 0f39e01 commit 24359e3
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
6 changes: 3 additions & 3 deletions rest_framework/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions rest_framework/generics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 24359e3

Please sign in to comment.