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