[Django]-How to order by nested objects fields?

2๐Ÿ‘

โœ…

As you are using django-rest-framework you have to use ordering_fields as you can see from the documentation here.Hope it helps example:

class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = (filters.OrderingFilter,)
    ordering_fields = ('username', 'email')
    ordering = ('created_on') # for reverse ordering = ('-created_on')

If an ordering attribute is set on the view, this will be used as the default ordering.

Typically youโ€™d instead control this by setting order_by on the initial queryset, but using the ordering parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template

5๐Ÿ‘

You can try specifying product__id to perform ordering based on the id of product.

orderby = product__id

Specify ordering_fields in your viewset.

ordering_fields = ('product__id', )

Leave a comment