Skip to content
thesarfo

Note

Model Serializers

Removing duplication between a model and its serializer by using ModelSerializer with a Meta class.

views 0

Now you know that everything in our serializers file also exist in our model class. There are 2 places where we are defining this models and their validation rules, so if we decide to change the validation rule for one of them, we need to do the same thing to the other

This is where we use model serializers. Using a model serializer class, we can create a model serializer without all this duplication. see below

class ProductSerializer(serializers.ModelSerializer):
'''we create a meta class and inside it we create a reference of the model we're serializing, and then we specify the fields in the model that we want to return'''
class Meta:
model = Product
fields = ['id', 'title', 'unit_price', 'price_with_tax', 'collection']
price_with_tax = serializers.SerializerMethodField(method_name='calculate_tax')
def calculate_tax(self, product: Product):
return product.unit_price * Decimal(1.1)