Model Serializer - Django Rest framework
Often we will want our serializer to map closely to Django model definition. In such cases, the rest framework provides a ModelSerializer class which helps to automatically generate a serializer class that corresponds to the model fields.
The model serializer has the following differences to regular serializer:
- On the basis of model, sets of fields are generated automatically.
- Generates validators automatically such as unique and unique together.
- It comes with basic .create() and .update() implementations.
What declaring a model serializer looks like:
1
2
3
4
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = ['id', 'first_name', 'last_name', 'email']
Now, all the fields of model Student gets mapped into corresponding fields as said earlier. And the foreign key relationship converts into a PrimaryKeyRelatedField.
Now let’s inspect ModelSerializer
Our Model Serializer looks different than the regular serializer until we see its representation.
We can see that underneath the representation of ModelSerializer is also same as regular serializer. The advantage with ModelSerializer is that it provides shortcut to automatically build serializer, saving time and increasing efficiency.
Leave a comment