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

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

Item.objects.all().order_by('spec__identifier')
2

Please try following code.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest