Skip to content

Cursor pagination #2428

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Jan 22, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 11 additions & 13 deletions rest_framework/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ class OrderingFilter(BaseFilterBackend):
ordering_param = api_settings.ORDERING_PARAM
ordering_fields = None

def get_ordering(self, request):
def get_ordering(self, request, queryset, view):
"""
Ordering is set by a comma delimited ?ordering=... query parameter.

Expand All @@ -124,15 +124,21 @@ def get_ordering(self, request):
"""
params = request.query_params.get(self.ordering_param)
if params:
return [param.strip() for param in params.split(',')]
fields = [param.strip() for param in params.split(',')]
ordering = self.remove_invalid_fields(queryset, fields, view)
if ordering:
return ordering

# No ordering was included, or all the ordering fields were invalid
return self.get_default_ordering(view)

def get_default_ordering(self, view):
ordering = getattr(view, 'ordering', None)
if isinstance(ordering, six.string_types):
return (ordering,)
return ordering

def remove_invalid_fields(self, queryset, ordering, view):
def remove_invalid_fields(self, queryset, fields, view):
valid_fields = getattr(view, 'ordering_fields', self.ordering_fields)

if valid_fields is None:
Expand All @@ -152,18 +158,10 @@ def remove_invalid_fields(self, queryset, ordering, view):
valid_fields = [field.name for field in queryset.model._meta.fields]
valid_fields += queryset.query.aggregates.keys()

return [term for term in ordering if term.lstrip('-') in valid_fields]
return [term for term in fields if term.lstrip('-') in valid_fields]

def filter_queryset(self, request, queryset, view):
ordering = self.get_ordering(request)

if ordering:
# Skip any incorrect parameters
ordering = self.remove_invalid_fields(queryset, ordering, view)

if not ordering:
# Use 'ordering' attribute by default
ordering = self.get_default_ordering(view)
ordering = self.get_ordering(request, queryset, view)

if ordering:
return queryset.order_by(*ordering)
Expand Down
Loading