[Django]-Django Rest Framework: Order by Serializer Method Field

6👍

As far as I can understand from your question you want to order the Assets by the current employee name. Let’s take few names for example:

  • Jean d’Artagnan (first_name: Jean, last_name: d’Artagnan)
  • Joe Plumber (first_name: Joe, last_name: Plumber)
  • Jonas Meyer (first_name: Jonas, last_name: Meyer)

The same ordering can be achieved if we sort first by first_name and then by last_name. In case there are multiple entries with the same first_name the ordering will be done be the last_name.

To achieve this you can simply specify the ordering_fields in your view:

class AssetsView(generics.ListCreateAPIView):
    filters = [filters.OrderingFilter]
    ordering_fields = ['current_employee.first_name', 'current_employee.last_name']
👤cezar

Leave a comment