Django Ordering by Property Field
I'm Using 'Orderingfilter' to Allow Ordering. According to Django Documentation, When Not Specifying 'Ordering_Fields' You Can Order by Any Field That...
I'm using 'OrderingFilter' to allow ordering. According to Django documentation, when not specifying 'ordering_fields' you can order by any field that mentioned in the view serializer. I have a field which is basically a @property field in the serializer. But when trying to order by that field, I get the following error:
Cannot resolve keyword 'spec_identifier' into field. Choices are:....
This is part of the model view:
class ItemViewSet(BaseViewMixin, MyModelView):
permission_classes = [MyItemViewPermissions]
serializer_class = ItemSerializer
filter_backends = (ItemFilter, OrderingFilter,)
and this is the property definition I want to order by:
@property
def spec_identifier(self):
return self.spec.identifier if self.spec else None
Is it possible to order by it?
3 Answers
So, after research and trial and error, that was the solution:
ordering_fields = tuple(serializer_class.Meta.fields + ['spec__identifier'])
you can order and get in values property, but you can order by related field, for example
Item.objects.all().order_by('spec__identifier')
Please try following code.
class ItemViewSet(BaseViewMixin, MyModelView):
permission_classes = [MyItemViewPermissions]
serializer_class = ItemSerializer
filter_backends = (ItemFilter, OrderingFilter,)
ordering_fields = ('spec__identifier',)