What is a Django Model?
A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. In Django, models are Python classes that subclass django.db.models.Model. Django uses these classes to automatically create the database tables for you via the ORM (Object-Relational Mapper).
- Defining Fields
Each attribute of the model represents a database field. Django provides a wide variety of field types that handle validation and SQL mapping automatically.
- Database Relationships
Django handles the three most common types of database relationships with ease: One-to-Many, Many-to-Many, and One-to-One.
- ForeignKey: Defines a many-to-one relationship (e.g., many Tasks belong to one Project).
- ManyToManyField: Defines a many-to-many relationship (e.g., a Project can have many Tags, and a Tag can be on many Projects).
- OneToOneField: Defines a one-to-one relationship (e.g., a User has exactly one Profile).
- Migrations: Evolving Your Schema
Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. It’s a two-step process:
Common Model Fields
| Field Type | Usage | SQL Equivalent |
|---|---|---|
| CharField | Short to medium strings | VARCHAR |
| TextField | Large amounts of text | TEXT / LONGTEXT |
| EmailField | Strings with email validation | VARCHAR |
| DateTimeField | Date and time objects | DATETIME |
| DecimalField | Fixed-precision decimals (Money) | DECIMAL |
| SlugField | URL-friendly strings (hyphenated) | VARCHAR |