How to change default Order from ASC to DESC in django OrderFilter

45 Views Asked by At

I am not an expert django dev. I was trying to write a viewset which has the ordering_fields and ordering fields, but this ordering field does not have any effect. My viewset is,

class ContentViewSet(viewsets.ModelViewSet):
    queryset = Content.objects.all()
    serializer_class = ContentSerializer
    filter_backends = [OrderingFilter]
    ordering_fields = ['created_at']
    ordering = ['-created_at']

What I am looking for is, it will provide the list in descending order. However, if I add a negative sign infront of created_at in the url, it gives me what I am looking for, but I was looking for a solution where I will get the same result without using that negative sign in the url.

Thanks in advance.

1

There are 1 best solutions below

1
paria On

You can use model Meta options. For ordering objects, you may simply add this piece of code to your model class:

class Meta:
    ordering = ["-created_at"]