Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 476
user3236034 Avatar asked Feb 06 '14 05:02

user3236034


People also ask

Do we need Serializers in Django REST framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

How do you pass extra context data to Serializers in Django REST framework?

In function-based views, we can pass extra context to serializer with “context” parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with “self. context”. From example, to get “exclude_email_list” we just used code 'exclude_email_list = self.

What is Serializers SerializerMethodField ()?

SerializerMethodField. This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. Signature: SerializerMethodField(method_name=None)

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.


1 Answers

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',)
like image 104
Tuo Lei Avatar answered Sep 28 '22 08:09

Tuo Lei