Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to use serializer as query parameters validators?

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'})
like image 938
Žilvinas Rudžionis Avatar asked Sep 15 '17 08:09

Žilvinas Rudžionis


People also ask

Why do we use Serializers?

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.

What is difference between serializer and ModelSerializer?

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 .

Is serializer necessary in Django?

It is not necessary to use a serializer.

How do I know if my serializer is valid?

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".


1 Answers

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.

like image 156
arjunattam Avatar answered Sep 27 '22 22:09

arjunattam