Skip to content

Chapter 2 of 8

Models, ORM, and Migrations

Django models are Python classes that subclass django.db.models.Model, with each model mapping to a single database table and each class attribute representing a database column. The framework provides a rich set of field types to handle different kinds of data: CharField for short text requiring a max_length, TextField for longer text, IntegerField for integers, BooleanField for True/False values, DateTimeField for date and time values, ForeignKey for many-to-one relationships, and ManyToManyField for many-to-many relationships. Additional behavior can be configured at the field level using null=True to allow NULL values at the database column level, and blank=True to permit empty values in forms.

A model can also include a Meta inner class to hold model-level options that do not define database fields but affect the model's behavior. Common Meta options include ordering for default queryset ordering, verbose_name for human-readable naming, db_table to override the table name, unique_together for composite uniqueness, indexes for defining database indexes, and constraints for declaring database-level integrity rules such as UniqueConstraint and CheckConstraint. Defining a __str__ method on a model is important because it returns a human-readable string representation used by the Django admin, the shell, and default ModelChoiceField rendering. Adding db_index=True to a field creates a single-column index, while Meta.indexes allows composite indexes for query optimization. The default database backend is SQLite via django.db.backends.sqlite3, while production deployments typically switch to PostgreSQL, MySQL, or Oracle by adjusting the DATABASES setting.

Relationships between models are defined using specialized field types. A ForeignKey represents a many-to-one relationship and accepts an on_delete argument that specifies behavior when the referenced object is deleted. Common on_delete options include CASCADE to delete dependents, PROTECT to block deletion, SET_NULL to set the foreign key to NULL (requiring null=True), SET_DEFAULT to set it to a default value, and DO_NOTHING to take no action. The related_name argument sets the reverse accessor name from the related model, defaulting to <modelname>_set if not specified. A OneToOneField represents a strict 1:1 link and is commonly used to extend the User model with a Profile. A ManyToManyField creates an auto-generated join table, but a custom through model can be specified to store additional fields on the relationship. Migrations are Django's version-controlled changes to the database schema, created with python manage.py makemigrations and applied with python manage.py migrate, with rollback possible by specifying a previous migration name.

All chapters
  1. 1Django Fundamentals and Project Layout
  2. 2Models, ORM, and Migrations
  3. 3Advanced Querying and Optimization
  4. 4Views, URLs, and Responses
  5. 5Templates and the Presentation Layer
  6. 6Forms, Admin, and Authentication
  7. 7Middleware, Security, and File Handling
  8. 8DRF, Signals, Testing, and More

Drill it

Reading is not remembering. These come from the Django Framework deck:

Q

What is Django?

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It follows the MTV (Model-Template-View) architectura...

Q

What is the Django MTV pattern?

MTV stands for Model-Template-View:Model – defines data structure and database schemaTemplate – handles the presentation layer (HTML)View – contains business lo...

Q

How do you create a new Django project?

Use the command:django-admin startproject myprojectThis generates the project directory with settings.py, urls.py, wsgi.py, asgi.py, and manage.py.

Q

How do you create a new Django app?

Run:python manage.py startapp myappThen add 'myapp' to the INSTALLED_APPS list in settings.py to register it with the project.