0
0
Djangoframework~30 mins

Custom serializer fields in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom Serializer Fields in Django REST Framework
📖 Scenario: You are building a simple API for a bookstore. Each book has a title and a price stored as an integer number of cents. You want to show the price in dollars with two decimal places in the API response.
🎯 Goal: Create a Django REST Framework serializer with a custom field that converts the price from cents (integer) to a formatted string in dollars (e.g., '12.99').
📋 What You'll Learn
Create a dictionary called book_data with keys 'title' and 'price_cents' and values 'Django for Beginners' and 2599 respectively.
Create a class called PriceField that subclasses serializers.Field.
Implement the to_representation method in PriceField to convert cents to a string in dollars with two decimals.
Create a serializer class called BookSerializer that uses PriceField for the price field and includes the title field.
💡 Why This Matters
🌍 Real World
APIs often need to present data in a format that is easy for users to understand. Custom serializer fields let you control how data is shown without changing the database.
💼 Career
Knowing how to write custom serializer fields is useful for backend developers working with Django REST Framework to build clean, user-friendly APIs.
Progress0 / 4 steps
1
Create the initial book data dictionary
Create a dictionary called book_data with keys 'title' and 'price_cents' and values 'Django for Beginners' and 2599 respectively.
Django
Need a hint?

Use curly braces to create a dictionary with the exact keys and values.

2
Create a custom serializer field class
Create a class called PriceField that subclasses serializers.Field.
Django
Need a hint?

Define a class with the exact name PriceField and inherit from serializers.Field.

3
Implement the to_representation method
Inside the PriceField class, implement the to_representation method that takes value (price in cents) and returns a string formatted as dollars with two decimals (e.g., '25.99').
Django
Need a hint?

Divide the integer value by 100 and format it as a string with two decimal places using an f-string.

4
Create the BookSerializer using the custom field
Create a serializer class called BookSerializer that subclasses serializers.Serializer. Add a title field as serializers.CharField() and a price field using the custom PriceField.
Django
Need a hint?

Define the serializer class with the exact name and add the two fields as shown. Use source='price_cents' for the price field to map to the correct key in the data.