0
0
Djangoframework~30 mins

Serializer validation in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Serializer validation
📖 Scenario: You are building a simple Django REST API for a bookstore. You want to ensure that the data sent to your API is valid before saving it to the database.
🎯 Goal: Create a serializer for a Book model and add validation to check that the price is not negative.
📋 What You'll Learn
Create a serializer class for the Book model
Add a field for title and price
Add a validation method to ensure price is zero or positive
Raise a validation error if price is negative
💡 Why This Matters
🌍 Real World
APIs often need to check data before saving to avoid errors or bad data in the database.
💼 Career
Knowing how to add validation in serializers is essential for backend developers working with Django REST Framework.
Progress0 / 4 steps
1
Create the BookSerializer class
Create a serializer class called BookSerializer that inherits from serializers.Serializer. Add two fields: title as a serializers.CharField() and price as a serializers.FloatField().
Django
Need a hint?

Remember to import serializers from rest_framework and define the fields inside the class.

2
Add a validation method for price
Inside the BookSerializer class, add a method called validate_price that takes self and value as parameters.
Django
Need a hint?

The validation method should return the value if it is valid.

3
Add validation logic to check for negative price
Inside the validate_price method, add an if statement to check if value is less than 0. If it is, raise serializers.ValidationError with the message "Price cannot be negative". Otherwise, return the value.
Django
Need a hint?

Use an if statement to check the value and raise the error if needed.

4
Complete the serializer with validation
Ensure the BookSerializer class includes the title and price fields and the validate_price method with the negative price check and error raising.
Django
Need a hint?

Review the whole class to ensure all parts are included correctly.