[Fixed]-Django rest framework , order_by a JSON from serializers.py file


There’s an easy way, just override it explicitly by add a ordering line:

class EstablecimientoViewSet(viewsets.ModelViewSet):
    queryset = Establecimiento.objects
    serializer_class = EstablecimientoSerializer
    filter_backends = (filters.DjangoFilterBackend, filters.OrderingFilter)
    ordering = ('nombre',) #add this line
    filter_fields = ('categoria','categoria__titulo',)


You don’t use the serializer for ordering. You need to use queryset attribute in your view like so:

class EstablecimientoListView(generics.ListCreateAPIView):
    queryset = Establecimiento.objects.order_by('nombre')
    serializer_class = EstablecimientoSerializer

    def filter_queryset(self, request, queryset, view):
        qs = super(EstablecimientoListView, self).filter_queryset(request, queryset, view)
        qs = qs.order_by('nombre')
        return qs

Leave a comment