diff --git a/rest_framework/filters.py b/rest_framework/filters.py index 429b79c77..aea9d3a57 100644 --- a/rest_framework/filters.py +++ b/rest_framework/filters.py @@ -11,6 +11,7 @@ from functools import reduce from django.core.exceptions import ImproperlyConfigured from django.db import models from django.db.models.constants import LOOKUP_SEP +from django.db.models.sql.constants import ORDER_PATTERN from django.template import loader from django.utils import six from django.utils.encoding import force_text @@ -268,7 +269,7 @@ class OrderingFilter(BaseFilterBackend): def remove_invalid_fields(self, queryset, fields, view, request): valid_fields = [item[0] for item in self.get_valid_fields(queryset, view, {'request': request})] - return [term for term in fields if term.lstrip('-') in valid_fields] + return [term for term in fields if term.lstrip('-') in valid_fields and ORDER_PATTERN.match(term)] def filter_queryset(self, request, queryset, view): ordering = self.get_ordering(request, queryset, view) diff --git a/tests/test_filters.py b/tests/test_filters.py index 15eb2ccf3..b2de80998 100644 --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -773,13 +773,14 @@ class OrderingFilterTests(TestCase): ordering_fields = ('text',) view = OrderingListView.as_view() - request = factory.get('/', {'ordering':'--text'}) + request = factory.get('/', {'ordering': '--text'}) response = view(request) assert response.data == [ {'id': 3, 'title': 'xwv', 'text': 'cde'}, {'id': 2, 'title': 'yxw', 'text': 'bcd'}, {'id': 1, 'title': 'zyx', 'text': 'abc'}, ] + def test_incorrectfield_ordering(self): class OrderingListView(generics.ListAPIView): queryset = OrderingFilterModel.objects.all() @@ -899,6 +900,7 @@ class OrderingFilterTests(TestCase): queryset = OrderingFilterModel.objects.all() filter_backends = (filters.OrderingFilter,) ordering = ('title',) + # note: no ordering_fields and serializer_class specified def get_serializer_class(self):