Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django serializers: What does is_valid actually do?

git repo: django tutorial

I've been following the above django project that looks at creating at person to person chat. I've come across this part:

def message_list(request, sender=None, receiver=None):
    ...

    elif request.method == 'POST':
        print('posting')
        data = JSONParser().parse(request)
        print(data)
        serializer = MessageSerializer(data=data)
        print(serializer)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)

class MessageSerializer(serializers.ModelSerializer):
    sender = serializers.SlugRelatedField(many=False, slug_field='email', queryset=User.objects.all())
    receiver = serializers.SlugRelatedField(many=False, slug_field='email', queryset=User.objects.all())

    class Meta:
        model = Message
        fields = ['sender', 'receiver', 'message', 'timestamp']

What does "if serializer.is_valid():" actually do? Is it checking that the data in the message matches the data in the user profile? I've never used serializers before and could use an explanation of it.

Thanks

like image 857
Micah Pearce Avatar asked Apr 14 '18 04:04

Micah Pearce


People also ask

What is Is_valid () do in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

What do Serializers do in Django?

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.

Is serialization necessary in Django?

It is not necessary to use a serializer. You can do what you would like to achieve in a view. However, serializers help you a lot. If you don't want to use serializer, you can inherit APIView at a function-based-view.

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

You need to call is_valid during deserialization process before write data to DB. is_valid perform validation of input data and confirm that this data contain all required fields and all fields have correct types. If validation process succeded is_valid set validated_data dictionary which is used for creation or updating data in DB. Otherwise serializer's property errors will contain information about errors in input data, and you can send this information as HTTP response in your view.

like image 81
neverwalkaloner Avatar answered Oct 21 '22 04:10

neverwalkaloner