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?
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.
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.
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)
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.
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',)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With