Serializer would not be used for its intended purpose of creating some django model but it would be used for query parameters validation, creation of filtering query to elasticsearch, swagger documentation describing API.
from rest_framework import views, serializers, fields
from rest_framework.response import Response
class TestQueryParams(serializers.Serializer):
id = fields.IntegerField(min_value=0)
date = fields.DateField(format='%Y%m%d')
class TestView(views.APIView):
def get(self, request):
qp = TestQueryParams(data=request.query_params)
qp.is_valid(raise_exception=True)
# parameters would not be used to create some model
# but they would be used to get data
return Response({'some': 'data'})
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.
The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators. It includes simple default implementations of .
It is not necessary to use a serializer.
We can validate the serializer by calling the method " is_valid() ". It will return the boolean(True/False) value. If the serializer is not valid then we can get errors by using the attribute "errors".
Definitely a good practice, since the serializer will automatically validate the fields, and raise the right exception if required.
The alternative is to either manually define these validations in the view, or worse - have your APIs return 500 server errors whenever an incorrect input is sent.
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