1.DRF architecture, Serializers, ModelSerializer, and fields
DRF layers a parallel set of building blocks over Django's own request/view/model — Serializers (translate between Python/model objects and JSON, plus validation), Views/ViewSets (the request-handling layer), and Routers (auto-generate URLs from a ViewSet) — each mirroring a Django concept while adding API-specific behavior. A Serializer is DRF's equivalent of a Form: fields declared explicitly, is_valid() runs validation, .data produces JSON-ready output. ModelSerializer is DRF's equivalent of ModelForm — it auto-generates fields from a model's own fields, inferring type and validators (e.g. a CharField's max_length becomes an automatic length validator) the same way ModelForm does, dramatically cutting boilerplate for the common "expose this model over an API" case.
Key features
- A plain Serializer requires every field declared explicitly (like Form) — full control, more boilerplate; ModelSerializer auto-generates fields from Meta.model + Meta.fields (like ModelForm) — less boilerplate, less explicit
- ModelSerializer infers field TYPE and VALIDATORS from the model field automatically — a model's CharField(max_length=100) becomes a serializer CharField with an automatic max_length=100 validator, without repeating it
- Meta.fields = "__all__" is supported but discouraged in DRF's own docs for anything beyond a quick prototype — an explicit field list is the documented recommendation, since it avoids silently exposing a newly-added model field over the API
- serializer.data (read) is only meaningful AFTER validation for deserialization, or directly for serialization — accessing .data before calling is_valid() on a bound serializer being used for input raises an AssertionError, a common early mistake
- DRF ships a broad field-type library (CharField, IntegerField, SlugRelatedField, PrimaryKeyRelatedField for relationships, etc.) — ModelSerializer picks a sensible default per model field type, but an explicit field declaration always overrides the inferred one
- DRF is a separate INSTALLED_APPS entry (rest_framework) with its own settings namespace (REST_FRAMEWORK = {...} in settings.py) — it layers on top of Django, it does not replace any part of Django's own request/URL/model machinery
DRF's Django-shaped analogues
- Django
- Form / ModelForm
- View
- DRF
- Serializer / ModelSerializer
- APIView / ViewSet
- Router
Command
class MySerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ["field1", "field2"]DRF mirrors Django's own shapes: Serializer:Form, ModelSerializer:ModelForm, APIView/ViewSet:View. ModelSerializer infers field type and validators from the model, the same way ModelForm does — an explicit field list (never "__all__") keeps the API surface a deliberate, reviewable decision rather than tied automatically to the model's current fields. Always call is_valid() before reading .data/.validated_data on an input serializer.