Django Ordering by property field

Viewed 4491

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'])
Related