Django Ordering by property field

5.7k views Asked by At

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

There are 3 answers

1
user2880391 On BEST ANSWER

So, after research and trial and error, that was the solution:

ordering_fields = tuple(serializer_class.Meta.fields + ['spec__identifier'])
2
AudioBubble On

you can order and get in values property, but you can order by related field, for example

Item.objects.all().order_by('spec__identifier')
0
Vaibhav Mule On

Please try following code.

class ItemViewSet(BaseViewMixin, MyModelView):
    permission_classes = [MyItemViewPermissions]
    serializer_class = ItemSerializer
    filter_backends = (ItemFilter, OrderingFilter,) 
    ordering_fields = ('spec__identifier',)