liveBook · Manning

ModelSchema

As explained in Django in Action

ModelSchema is a Django Ninja schema class that derives field definitions and requiredness from a Django ORM model.

ModelSchema is Django Ninja’s shortcut for turning a Django ORM model into a schema for JSON serialization. Instead of redeclaring every model field, subclass ModelSchema, point its inner Meta class at the model, and choose the fields that an API endpoint should expose. It plays a role similar to ModelForm, but its job is API data rather than HTML forms. section 11.2.1

A response schema tells Ninja how to serialize the value returned by an endpoint. If an endpoint returns Promoter objects, response=list[PromoterSchema] means Ninja serializes each object using the selected fields. The view can return a queryset; Ninja handles the translation to JSON. section 11.2.1

Listing 11.4 Serialize an ORM Model class with Ninja ModelSchema
# RiffMates/promoters/api.py
from ninja import Router, ModelSchema

from promoters.models import Promoter

router = Router()  #1

class PromoterSchema(ModelSchema):  #2
    class Meta:
        model = Promoter  #3
        fields = ["id", "full_name", "birth", "death"]  #4

@router.get("/promoters/",
        response=list[PromoterSchema])  #5
def promoters(request):
    return Promoter.objects.all()   #6

This endpoint exposes a promoter list. Meta.model selects the ORM model, Meta.fields limits the JSON fields, and the response declaration applies the schema to every returned object. section 11.2.1

A ModelSchema can also add computed fields that do not exist on the model. Declare the field with a Python type hint, then provide a static resolve_ method whose name matches it. A Venue schema adds a readable slug and a URL while still deriving id, name, and description from Venue. section 11.2.2 section 11.5

Choose the schema shape to match the operation:

  • Use a ModelSchema-derived output schema when returning model objects from GET, PUT, or similar endpoints. section 11.2.1 section 11.2.7
  • Use the model-derived requiredness for full updates with PUT, where clients provide all required fields. section 11.2.7
  • Create a separate hand-written schema with Optional type hints for PATCH, because changed fields must be optional. section 11.2.7

Adding API-only Venue data

VenueOut selects id, name, and description from Venue, then adds slug: str and url: str. resolve_slug builds a slug from the venue name and ID; resolve_url reverses the endpoint URL. A GET request can therefore return database fields plus useful API navigation data. section 11.2.2

How Django in Action covers it

How deep it goes
Explains Meta configuration, response use, computed resolver fields, and requiredness; defers PATCH schemas to hand-written Optional fields.
Examples
Uses PromoterSchema for promoter lists and VenueOut for a venue with computed slug and URL fields.
What it assumes
Builds from Django ORM models while introducing schema declarations and Python type hints for serialization.
What you can do after
Apply it via Django Ninja to expose selected model fields and computed values from API endpoints.
How it connects
Connects Django ORM models, Ninja Schema, Pydantic, Python type hints, JSON serialization, PUT, PATCH, and resolver methods.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.