user3236034
user3236034

Reputation: 463

django rest framework , order_by a JSON from serializers.py file

I'm working with the django rest framework and I want make a order by to my json How I can make a order_by with django rest framework from the serializers.py file I have this in serializers.py

class EstablecimientoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Establecimiento
        depth = 1
        fields =   ('nombre','ciudad',)
    order_by = (
        ('nombre',)
    )

I have this order_by but this does nothing with the JSON

What is the correct way to do this order by in the JSON from serializers.py?

I have in views.py

class EstablecimientoViewSet(viewsets.ModelViewSet):
    queryset = Establecimiento.objects.order_by('nombre')
    serializer_class = EstablecimientoSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filter_fields = ('categoria','categoria__titulo',)

Then the order_by not work because I have this filter, How I can do to make the filter work well with order_by?

Upvotes: 13

Views: 10127

Answers (2)

Tuo Lei
Tuo Lei

Reputation: 101

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',)

Upvotes: 10

mariodev
mariodev

Reputation: 15494

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

Upvotes: 1

Related Questions