serializer.data when serializing the user instance?from rest_framework import serializers class UserSerializer(serializers.Serializer): id = serializers.IntegerField() username = serializers.CharField(max_length=100) is_active = serializers.BooleanField(default=True) user = type('User', (), {'id': 1, 'username': 'alice', 'is_active': False})() serializer = UserSerializer(user)
The serializer reads the attributes from the user object as they are. Since is_active is set to False on the user, the output reflects that value. The serializer does not change the values, it just converts them to the specified types.
from rest_framework import serializers class AuthorSerializer(serializers.Serializer): name = serializers.CharField(max_length=100) class PostSerializer(serializers.Serializer): title = serializers.CharField(max_length=200) author = ??? # Fill this line correctly
To validate nested data, you embed one serializer inside another by assigning the nested serializer as a field. Using AuthorSerializer() inside PostSerializer allows validation of the nested author dictionary.
serializer.is_valid() raise a ValidationError?from rest_framework import serializers class ProductSerializer(serializers.Serializer): name = serializers.CharField(max_length=50) price = serializers.DecimalField(max_digits=5, decimal_places=2) input_data = {'name': 'Pen', 'price': '12.345'} serializer = ProductSerializer(data=input_data) serializer.is_valid(raise_exception=True)
The price field allows only 2 decimal places, but the input has 3 decimal places ('12.345'). This causes a validation error.
serializer.validated_data after validation?serializer.validated_data contain after calling serializer.is_valid()?from rest_framework import serializers class CommentSerializer(serializers.Serializer): text = serializers.CharField() likes = serializers.IntegerField(default=0) input_data = {'text': 'Nice post!'} serializer = CommentSerializer(data=input_data) serializer.is_valid()
The likes field has a default value of 0, so if it is missing in input data, the serializer adds it with the default value in validated_data.
create() method is true?create() method in a serializer, which statement is correct?create() in the serializer lifecycle during object creation.The create() method is responsible for creating and returning a new model instance using the validated data. It is called by serializer.save() after validation.