Member-only story
How to use Serializer Effectively in Django Part-2
4 min readOct 9, 2022
My article is for everyone! Non-members can click on this link and jump straight into the full text!!
This article is a continuation of my first article How to use Serializer Effectively in Django In this article we are going to see more on how to modify the default behavior of the serializer class.
3. How to write validation in ModelSerializer class.
- Consider a situation where a student can only participate if his/her age is at least 18 years old.
- We can also declare the validation while creating the Django models class and that will be going to inherit by ModelSerializer class.
- But let’s see how to implement validation in the serializer class.
class StudentsSerializer(serializers.ModelSerializer):
name = serializers.SerializerMethodField()
class Meta:
model= Students
fields = ('first_name', 'last_name' , 'name','age','gender')
extra_kwargs = {
'first_name': {'write_only': True},
'last_name': {'write_only': True}
} def get_name(self, obj):
return f"{obj.first_name} {obj.last_name}" def validate_age(self, age):
if age < 18:
raise serializers.ValidationError('Student age should be…