From f64c592df34528bfc9a1c6503281c87f82ef35f7 Mon Sep 17 00:00:00 2001 From: masterfloda Date: Wed, 5 Jul 2017 16:06:08 -0700 Subject: [PATCH] https://github.com/AltSchool/dynamic-rest/issues/180 prefer get_serializer_class method to serializer_class attribute for getting ordering fields --- dynamic_rest/filters.py | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/dynamic_rest/filters.py b/dynamic_rest/filters.py index 439f8b2d..f2141653 100644 --- a/dynamic_rest/filters.py +++ b/dynamic_rest/filters.py @@ -651,15 +651,28 @@ def get_valid_fields(self, queryset, view, context={}): """ valid_fields = getattr(view, 'ordering_fields', self.ordering_fields) + # prefer the overriding method + if hasattr(view, 'get_serializer_class'): + try: + serializer_class = view.get_serializer_class() + except AssertionError: + # Raised by the default implementation if + # no serializer_class was found + serializer_class = None + # use the attribute + else: + serializer_class = getattr(view, 'serializer_class', None) + + # neither a method nor an attribute has been specified + if serializer_class is None: + msg = ( + "Cannot use %s on a view which does not have either a " + "'serializer_class' or an overriding 'get_serializer_class'." + ) + raise ImproperlyConfigured(msg % self.__class__.__name__) + if valid_fields is None or valid_fields == '__all__': # Default to allowing filtering on serializer fields - serializer_class = getattr(view, 'serializer_class') - if serializer_class is None: - msg = ( - "Cannot use %s on a view which does not have either a " - "'serializer_class' or 'ordering_fields' attribute." - ) - raise ImproperlyConfigured(msg % self.__class__.__name__) valid_fields = [ (field_name, field.source or field_name) for field_name, field in serializer_class().fields.items() @@ -668,7 +681,6 @@ def get_valid_fields(self, queryset, view, context={}): ) and not field.source == '*' ] else: - serializer_class = getattr(view, 'serializer_class') valid_fields = [ (field_name, field.source or field_name) for field_name, field in serializer_class().fields.items()