The project’s Category, Transaction, and Budget models have been complete since episode 2 and proven correct by tests in episode 5 — but clients (web or mobile) don’t understand Python objects; they only talk to each other in JSON. In this episode, we write Django REST Framework (DRF) serializers to convert between models and JSON in both directions, with validation like “amount must be positive.” A continuation of episode 5, “Writing Your First Tests for Models (TestCase)” — where the money logic was locked down — now we open the door for that data to go out through the API.
1. Installing Django REST Framework
DRF is the standard library for building REST APIs with Django; version 3.18 already supports Python 3.15. Install it:
pip install djangorestframework
Add it to INSTALLED_APPS in settings:
INSTALLED_APPS = [ # ... "rest_framework", "expenses",]
2. CategorySerializer — turning categories into JSON
Create the file expenses/serializers.py. A serializer is a class that declares which fields are allowed through the API — the rule of thumb: only expose the fields the client actually needs:
from rest_framework import serializersfrom .models import Categoryclass CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ["id", "name", "kind", "color"] read_only_fields = ["id"]
ModelSerializer auto-generates fields from the model with the correct data types (CharField, DecimalField, …), so you don’t have to declare each field by hand. The user field is deliberately left out of fields, because in episode 9 we will assign it automatically from request.user — the client must never get to choose the user.
3. TransactionSerializer — controlling money data
Transaction is the most sensitive model, so its serializer must block negative amounts right at the door:
from datetime import datefrom rest_framework import serializersfrom .models import Transactionclass TransactionSerializer(serializers.ModelSerializer): category_name = serializers.CharField(source="category.name", read_only=True) class Meta: model = Transaction fields = ["id", "category", "category_name", "amount", "occurred_on"] read_only_fields = ["id", "category_name"] def validate_amount(self, value): if value <= 0: raise serializers.ValidationError("Amount must be greater than 0.") return value def validate(self, attrs): occurred_on = attrs.get("occurred_on") instance_date = occurred_on or getattr(self.instance, "occurred_on", None) if instance_date and instance_date > date.today(): raise serializers.ValidationError( {"occurred_on": "Transaction date cannot be in the future."} ) return attrs
Two layers of validation: validate_amount blocks a single field as soon as it is parsed, while validate() checks relationships between fields (here: the date must not be in the future). DRF calls them in exactly this order before touching the database. The category_name field uses source="category.name" so the client can read the category name without an extra query — lighter and clearer than depth = 1.
4. Quick test in the Django shell
No views or URLs needed yet — check the serializer right in the shell:
python manage.py shell>>> from expenses.models import Category>>> from expenses.serializers import CategorySerializer>>> cat = Category.objects.first()>>> CategorySerializer(cat).data{'id': 1, 'name': 'Ăn uống', 'kind': 'expense', 'color': '#F97316'}>>> s = CategorySerializer(data={"name": "", "kind": "expense", "color": "#F97316"})>>> s.is_valid()False>>> s.errors{'name': [ErrorDetail(string='This field may not be blank.', code='blank')]}
See: serializing an object is just .data, while incoming data is checked with is_valid() — errors come back tied to the right field with the right error code. This is exactly the mechanism the API view in episode 7 will use.
Apply it to your project
A serializer is the boundary layer between the database and the outside world — keep this rule and you’ll save yourself headaches later: business logic (validators, unique constraints, on_delete) lives in the model; presentation formatting (showing the category name alongside the id, rounding amounts) lives in the serializer. Write a similar BudgetSerializer today — the Budget model already has the unique (user, category, year, month) constraint from episode 2, so its serializer mostly just declares fields, and you’ll reuse it in episode 11 when building monthly spending stats.
Related posts
- Building an Expense Tracker with Django #3: Customizing the Django admin to manage expenses
- Building an Expense Tracker with Django #4: Seeding sample data with fixtures and a management command
- Building an Expense Tracker with Django #5: Writing your first tests for models (TestCase)
Frequently asked questions
How is ModelSerializer different from a plain Serializer?
ModelSerializer auto-generates fields and validators from the model (max_length, unique, choices, …), with built-in create() and update(). A plain Serializer is for data not tied directly to a model — e.g. a login payload. For standard CRUD, ModelSerializer is always the first choice.
When should I use depth, and when should I write a separate nested serializer?
depth = 1 is quick for reads (showing nested objects), but it applies to every relationship, gives no field control, and can’t be used for writes. For control, declare an explicit nested serializer or use a read-only field like category_name above — lighter and clearer.
How do validate_<field> and validate() differ?
validate_amount receives a single value and runs first; validate() receives the whole dict after field validation, used to check relationships between fields (transaction date vs. today). Note: validate() doesn’t run if any field already failed — which is why you need both layers.
Does a serializer create records in the database by itself?
Yes — calling serializer.is_valid(raise_exception=True) followed by serializer.save() invokes ModelSerializer‘s create()/update(). But in a real API, assigning user must happen in the view (episode 9); the serializer only handles formatting and validating the data.
References
- Django REST Framework — Serializers: https://www.django-rest-framework.org/api-guide/serializers/
- Django REST Framework — ModelSerializer: https://www.django-rest-framework.org/api-guide/serializers/#modelserializer
