EthicsComputerCourses
Join training +91 90532 10052

Models & Serializers

Django + React · Lesson 5 of 20 Intermediate 12 min read Updated

By the end of this lesson BookShelf will have real data: Author, Book and Review models, sample books loaded from a fixture, and ModelSerializers that turn them into the JSON contract React uses. You will add validation that protects the database, and you will create books and reviews through the API with curl.

What you should know first: Django REST Framework Basics (this lesson continues its code), Models & the ORM, Migrations and QuerySets & Relationships. Versions used: Django 6.1.3 and Django REST Framework 3.18.3, with SQLite.

Step 1: the models

A model is a Python class that describes one database table. Put all three BookShelf models in books/models.py:

Python
from django.conf import settings
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models


class Author(models.Model):
    name = models.CharField(max_length=120, unique=True)
    bio = models.TextField(blank=True)

    class Meta:
        ordering = ["name"]

    def __str__(self):
        return self.name


class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author, on_delete=models.PROTECT, related_name="books")
    published_year = models.PositiveSmallIntegerField()
    summary = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["title"]

    def __str__(self):
        return f"{self.title} ({self.published_year})"


class Review(models.Model):
    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name="reviews")
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="reviews"
    )
    rating = models.PositiveSmallIntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(5)]
    )
    comment = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]
        constraints = [
            models.UniqueConstraint(fields=["book", "user"], name="one_review_per_user_per_book"),
        ]

    def __str__(self):
        return f"{self.user} rated {self.book} {self.rating}/5"

Each choice here is a rule that the database or Django will enforce for you:

  • on_delete=models.PROTECT on Book.author stops anyone deleting an author who still has books. Losing all of R. K. Narayan's books because someone deleted his name by mistake would be a disaster.
  • on_delete=models.CASCADE on reviews means that deleting a book deletes its reviews, which make no sense alone.
  • settings.AUTH_USER_MODEL points to our custom user from Project Structure for Django + React.
  • The unique constraint allows one review per user per book. It lives in the database, so even a bug in the API cannot create a duplicate.
  • related_name="reviews" lets you write book.reviews.all(), and, as you will see, count and average them in one query.

Step 2: migrate and load sample data

Terminal
python manage.py makemigrations books
python manage.py migrate books
Output
Migrations for 'books':
  books\migrations\0001_initial.py
    + Create model Author
    + Create model Book
    + Create model Review
Operations to perform:
  Apply all migrations: books
Running migrations:
  Applying books.0001_initial... OK

Typing sample books into the admin every time you reset the database gets boring. A fixture is a JSON file of rows that Django can load with one command. Create books/fixtures/sample_books.json:

JSON
[
  {"model": "books.author", "pk": 1, "fields": {"name": "R. K. Narayan", "bio": ""}},
  {"model": "books.author", "pk": 2, "fields": {"name": "Premchand", "bio": ""}},
  {"model": "books.author", "pk": 3, "fields": {"name": "Arundhati Roy", "bio": ""}},
  {"model": "books.book", "pk": 1, "fields": {"title": "Swami and Friends", "author": 1, "published_year": 1935, "summary": "A schoolboy's adventures in the town of Malgudi.", "created_at": "2026-11-16T09:00:00+05:30"}},
  {"model": "books.book", "pk": 2, "fields": {"title": "Malgudi Days", "author": 1, "published_year": 1943, "summary": "", "created_at": "2026-11-16T09:00:00+05:30"}},
  {"model": "books.book", "pk": 3, "fields": {"title": "Godaan", "author": 2, "published_year": 1936, "summary": "", "created_at": "2026-11-16T09:00:00+05:30"}},
  {"model": "books.book", "pk": 4, "fields": {"title": "The God of Small Things", "author": 3, "published_year": 1997, "summary": "", "created_at": "2026-11-16T09:00:00+05:30"}}
]
Terminal
python manage.py loaddata sample_books
Output
Installed 7 object(s) from 1 fixture(s)

Fixtures hold made-up or public data only. Never put real users or passwords in one. Register the models in books/admin.py too, so staff can fix data by hand at /admin/:

Python
from django.contrib import admin

from books.models import Author, Book, Review


@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
    search_fields = ["name"]


@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    list_display = ["title", "author", "published_year"]
    list_select_related = ["author"]
    search_fields = ["title", "author__name"]


@admin.register(Review)
class ReviewAdmin(admin.ModelAdmin):
    list_display = ["book", "user", "rating", "created_at"]

Step 3: ModelSerializers

In the last lesson you listed every field of a Serializer by hand. A ModelSerializer reads the model and builds the fields for you, including types, lengths, unique checks and validators. You only choose which fields to include and add the extras. Add these to books/serializers.py, below ReadingTimeSerializer:

Python
from django.utils import timezone
from rest_framework import serializers

from books.models import Author, Book, Review


class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ["id", "name", "bio"]


class BookSerializer(serializers.ModelSerializer):
    author_name = serializers.CharField(source="author.name", read_only=True)
    average_rating = serializers.FloatField(read_only=True, allow_null=True)
    review_count = serializers.IntegerField(read_only=True, default=0)

    class Meta:
        model = Book
        fields = [
            "id", "title", "author", "author_name", "published_year",
            "summary", "average_rating", "review_count", "created_at",
        ]
        read_only_fields = ["created_at"]

    def validate_published_year(self, value):
        this_year = timezone.now().year
        if value > this_year:
            raise serializers.ValidationError(f"Year cannot be after {this_year}.")
        return value

    def validate(self, attrs):
        title = attrs.get("title", getattr(self.instance, "title", None))
        author = attrs.get("author", getattr(self.instance, "author", None))
        same = Book.objects.filter(title__iexact=title, author=author)
        if self.instance:  # editing: ignore the book itself
            same = same.exclude(pk=self.instance.pk)
        if same.exists():
            raise serializers.ValidationError("This author already has a book with this title.")
        return attrs


class ReviewSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    username = serializers.CharField(source="user.username", read_only=True)

    class Meta:
        model = Review
        fields = ["id", "book", "user", "username", "rating", "comment", "created_at"]
        read_only_fields = ["created_at"]

Here is what each piece does for the API contract:

  • fields is an explicit list. Never use fields = "__all__". If someone later adds a field such as is_featured to Book, "__all__" would silently let any logged-in user set it through the API. This attack is called mass assignment. An explicit list means new fields stay private until you add them on purpose.
  • author and author_name. React sends the author's id and reads the name. source="author.name" follows the foreign key, and read_only=True means clients cannot change it.
  • validate_<field> methods check one field. Here, no book from the future.
  • validate(self, attrs) checks fields together and reports under non_field_errors. It also works for edits, where self.instance is the existing book.
  • HiddenField with CurrentUserDefault() fills user from the logged-in request. The client can never choose whose name a review is written under, and the field does not appear in the output. We show username instead.

You can ask DRF what a ModelSerializer built. In python manage.py shell, print(repr(ReviewSerializer())) prints:

Output
ReviewSerializer():
    id = BigIntegerField(label='ID', read_only=True)
    book = PrimaryKeyRelatedField(queryset=Book.objects.all(), required=True)
    user = HiddenField(default=CurrentUserDefault())
    username = CharField(read_only=True, source='user.username')
    rating = IntegerField(max_value=5, min_value=1)
    comment = CharField(allow_blank=True, required=False, style={'base_template': 'textarea.html'})
    created_at = DateTimeField(read_only=True)
    class Meta:
        validators = [<UniqueTogetherValidator(queryset=Review.objects.all(), fields=('book', 'user'))>]

DRF copied the 1 to 5 limits from the model's validators, and it turned the database's unique constraint into a UniqueTogetherValidator. So a duplicate review becomes a clean 400 message instead of a database crash.

Step 4: serializers in the shell

Before writing views, try both directions in python manage.py shell. Serialising first:

Python
from books.serializers import AuthorSerializer, BookSerializer

author = Author.objects.get(name="Premchand")
print(AuthorSerializer(author).data)

book = Book.objects.get(title="Godaan")
print(BookSerializer(book).data)
Output
{'id': 2, 'name': 'Premchand', 'bio': ''}
{'id': 3, 'title': 'Godaan', 'author': 2, 'author_name': 'Premchand', 'published_year': 1936, 'summary': '', 'average_rating': None, 'review_count': 0, 'created_at': '2026-11-16T09:00:00+05:30'}

Look closely at average_rating: None and review_count: 0. The model has no such columns. A plain Book.objects.get() does not calculate them, so the serializer falls back to None (allowed by allow_null=True) and the default 0. They only get real values from the view's queryset, which you will write in Step 5. Keep this in mind: a serializer can only show what the queryset gives it.

Now validating:

Python
s = BookSerializer(data={"title": "Nirmala", "author": 2, "published_year": 1927})
print(s.is_valid())
print(s.validated_data)

bad = BookSerializer(data={"title": "Gaban", "author": 42, "published_year": "soon"})
print(bad.is_valid())
print(bad.errors)
Output
True
{'title': 'Nirmala', 'author': <Author: Premchand>, 'published_year': 1927}
False
{'author': [ErrorDetail(string='Invalid pk "42" - object does not exist.', code='does_not_exist')], 'published_year': [ErrorDetail(string='A valid integer is required.', code='invalid')]}

The id 2 became a real Author object in validated_data, and the id 42 that does not exist was caught before anything touched the database.

Step 5: list and create through the API

DRF's generic views combine a queryset, a serializer and the standard behaviour. ListCreateAPIView answers GET with a list and POST by validating and saving. Add to books/views.py:

Python
from django.db.models import Avg, Count
from rest_framework import generics

from books.models import Book, Review
from books.serializers import BookSerializer, ReviewSerializer


class BookListCreate(generics.ListCreateAPIView):
    serializer_class = BookSerializer
    queryset = Book.objects.select_related("author").annotate(
        average_rating=Avg("reviews__rating"),
        review_count=Count("reviews"),
    ).order_by("title")


class ReviewListCreate(generics.ListCreateAPIView):
    serializer_class = ReviewSerializer
    queryset = Review.objects.select_related("user")

And the URLs in books/urls.py:

Python
urlpatterns = [
    path("reading-time/", views.reading_time, name="reading-time"),
    path("books/", views.BookListCreate.as_view(), name="book-list"),
    path("reviews/", views.ReviewListCreate.as_view(), name="review-list"),
]

The queryset does the heavy lifting. annotate() asks the database to compute each book's average rating and review count in the same query. select_related("author") fetches each book's author with a SQL join. Without it, author_name would cost one extra query per book: 100 books, 101 queries. This is the N+1 problem, the most common performance bug in DRF APIs. order_by("title") keeps the order fixed, because a grouped query does not use the model's default ordering.

Both views keep the project default IsAuthenticatedOrReadOnly: anyone can read, only logged-in users can write. We test writes with curl -u as in the last lesson. Priya is the admin user from that lesson; Kabir is a second user created the same way.

Terminal
curl -u priya:YOUR-PASSWORD -X POST http://127.0.0.1:8000/api/reviews/ -H "Content-Type: application/json" -d '{"book": 1, "rating": 5, "comment": "Swami feels like my own school days."}'
curl -u kabir:HIS-PASSWORD -X POST http://127.0.0.1:8000/api/reviews/ -H "Content-Type: application/json" -d '{"book": 1, "rating": 4, "comment": ""}'
Output
{"id":1,"book":1,"username":"priya","rating":5,"comment":"Swami feels like my own school days.","created_at":"2026-11-16T10:27:46.651756+05:30"}
{"id":2,"book":1,"username":"kabir","rating":4,"comment":"","created_at":"2026-11-16T10:27:50.643069+05:30"}

Both came back with 201 Created. The JSON had no user field: the server took it from the login. Now try to break the rules: Priya reviews the same book again, she sends a bad book id and rating, and an anonymous user tries to post.

Output
{"non_field_errors":["The fields book, user must make a unique set."]}
{"book":["Invalid pk \"99\" - object does not exist."],"rating":["Ensure this value is less than or equal to 5."]}
{"detail":"Authentication credentials were not provided."}

The first two are 400 responses and the last is 403. Books work the same way. A new book with extra spaces in the title, a duplicate, and a request full of mistakes:

Terminal
curl -u priya:YOUR-PASSWORD -X POST http://127.0.0.1:8000/api/books/ -H "Content-Type: application/json" -d '{"title": "  A Tiger for Malgudi ", "author": 1, "published_year": 1983}'
curl -u priya:YOUR-PASSWORD -X POST http://127.0.0.1:8000/api/books/ -H "Content-Type: application/json" -d '{"title": "godaan", "author": 2, "published_year": 1936}'
curl -u priya:YOUR-PASSWORD -X POST http://127.0.0.1:8000/api/books/ -H "Content-Type: application/json" -d '{"title": "", "author": 1, "published_year": 2031, "average_rating": 5}'
Output
{"id":5,"title":"A Tiger for Malgudi","author":1,"author_name":"R. K. Narayan","published_year":1983,"summary":"","average_rating":null,"review_count":0,"created_at":"2026-11-16T10:28:41.761543+05:30"}
{"non_field_errors":["This author already has a book with this title."]}
{"title":["This field may not be blank."],"published_year":["Year cannot be after 2026."]}

DRF's CharField trims spaces by default, so the title was saved cleanly. The duplicate check ignored case. And the "average_rating": 5 that the last request tried to sneak in was simply ignored, because the field is read-only. In our run, one more request created Waiting for the Mahatma (1955) with "review_count": 500 and "created_at": "2000-01-01T00:00:00Z" in the JSON. It came back with "review_count":0 and the real creation time: read-only fields are never written from input.

Finally, Kabir also reviewed Godaan. The list now carries correct numbers, because it comes from the annotated queryset. Printing just the id, title, average and count of each book:

Terminal
curl -s http://127.0.0.1:8000/api/books/ | python -c "import json,sys; [print(b['id'], b['title'], b['average_rating'], b['review_count']) for b in json.load(sys.stdin)]"
Output
5 A Tiger for Malgudi None 0
3 Godaan 5.0 1
2 Malgudi Days None 0
1 Swami and Friends 4.5 2
4 The God of Small Things None 0
6 Waiting for the Mahatma None 0

Run the shell code from Step 4 again now: BookSerializer(Book.objects.get(title="Godaan")).data still says None and 0, while the API says 5.0 from 1 review. Same serializer, different queryset.

Showing every kind of error in React

Your forms will meet three error shapes from this lesson: field errors, non_field_errors and detail. One small helper can turn any of them into a list of readable messages. This example uses the exact bodies the API returned above.

React JSXOpen in editor
import { createRoot } from "react-dom/client";

// Real error bodies from the BookShelf API
const responses = [
  { title: "Duplicate review", body: { non_field_errors: ["The fields book, user must make a unique set."] } },
  { title: "Bad book", body: { title: ["This field may not be blank."], published_year: ["Year cannot be after 2026."] } },
  { title: "Not logged in", body: { detail: "Authentication credentials were not provided." } },
];

const labels = { title: "Title", published_year: "Year", book: "Book", rating: "Rating" };

function errorMessages(data) {
  if (!data) return ["Something went wrong. Please try again."];
  if (typeof data.detail === "string") return [data.detail];
  return Object.entries(data).flatMap(([field, messages]) =>
    field === "non_field_errors"
      ? messages
      : messages.map((m) => `${labels[field] ?? field}: ${m}`)
  );
}

function ErrorBox({ title, data }) {
  return (
    <section style={{ border: "1px solid #b00020", padding: "4px 12px", marginBottom: 8 }}>
      <h2 style={{ fontSize: "1rem" }}>{title}</h2>
      <ul>
        {errorMessages(data).map((msg) => <li key={msg}>{msg}</li>)}
      </ul>
    </section>
  );
}

createRoot(document.getElementById("root")).render(
  <main>
    {responses.map((r) => <ErrorBox key={r.title} title={r.title} data={r.body} />)}
  </main>
);

The boxes show the unique-set message on its own, "Title: This field may not be blank." and "Year: Year cannot be after 2026." with friendly labels, and the login message. In a real form you would show field messages next to their inputs, as in the last lesson, and use a box like this for the rest.

Common mistakes

  • fields = "__all__". Opens every current and future column to writes. List fields explicitly.
  • Taking the owner from the JSON. A user field the client fills means anyone can post as anyone. Use HiddenField(default=CurrentUserDefault()) or set it in the view.
  • Forgetting select_related and annotate. The list still works, but with one query per row it slows down as data grows.
  • Expecting annotated fields everywhere. average_rating is only real when the queryset annotates it, as the shell test showed.
  • Deleting with CASCADE by habit. Choose PROTECT where losing related rows would hurt.

Interview questions

1. What does a ModelSerializer generate for you?

Fields with matching types and limits from the model, validators from model validators and unique constraints, and create() and update() methods that save instances. You still choose the field list and add custom fields and validation.

2. Why is fields = "__all__" risky?

It exposes every model field for reading and writing, including fields added later. A new internal field such as is_featured would become writable by any client, which is a mass assignment vulnerability. An explicit list keeps new fields private by default.

3. How do you make sure a review is saved for the logged-in user and not someone else?

Never accept the user from the request body. Use HiddenField(default=CurrentUserDefault()) in the serializer, or pass user=self.request.user to serializer.save() in the view. The client cannot change either.

4. What is the N+1 problem and how did BookShelf avoid it?

Listing N rows and then running one more query per row for related data gives N+1 queries. select_related("author") joins the author into the main query, and annotate() computes averages and counts in the database instead of per book.

5. What is the difference between validate_<field> and validate?

validate_<field> checks one field and reports errors under that field's name. validate(attrs) runs after all fields pass and can compare fields; its errors appear under non_field_errors.

Key points

  • Author, Book and Review live in the books app; reviews point to settings.AUTH_USER_MODEL.
  • Use PROTECT and CASCADE deliberately, and database constraints for rules that must never break.
  • Fixtures (loaddata) give every developer the same sample data.
  • ModelSerializers build fields from models; always list fields explicitly.
  • Read-only fields (author_name, average_rating, created_at) are ignored on input; HiddenField takes the user from the login.
  • Annotate and select_related in the view's queryset to get correct numbers without N+1 queries.

Exercise

Add a pages field to Book (a positive whole number, optional, because not every edition is known). Show it in the API, reject values above 3000 with the message "That is longer than any book on our shelf.", and add a read-only reading_days field that tells Rohan how many days the book takes at 20 pages a day, or null when pages is empty. Run the migration and test a POST with "pages": 4000.

Show solution
Python
# books/models.py (inside Book)
    pages = models.PositiveIntegerField(null=True, blank=True)

# books/serializers.py (inside BookSerializer)
    reading_days = serializers.SerializerMethodField()

    class Meta:
        model = Book
        fields = [
            "id", "title", "author", "author_name", "published_year", "pages",
            "reading_days", "summary", "average_rating", "review_count", "created_at",
        ]
        read_only_fields = ["created_at"]

    def get_reading_days(self, book):
        if book.pages is None:
            return None
        return -(-book.pages // 20)  # round up without importing math

    def validate_pages(self, value):
        if value is not None and value > 3000:
            raise serializers.ValidationError("That is longer than any book on our shelf.")
        return value

Run python manage.py makemigrations books and python manage.py migrate. A POST with "pages": 4000 returns 400 with {"pages":["That is longer than any book on our shelf."]}, and a book with 320 pages shows "reading_days": 16. SerializerMethodField is always read-only, so clients cannot set it.

Quick Quiz

1. Which on_delete stops an author from being deleted while they still have books?

2. A client sends "average_rating": 5 when creating a book. What happens?

3. Why did BookSerializer(book).data in the shell show review_count: 0 for a reviewed book?

4. Where does a duplicate review's error appear in the response?

Learn Django + React with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call