Definition
Models are Python classes that define the structure and behavior of data in a Django application. They serve as the single, definitive source of truth about your data.
Why It Matters
Databases are the “long-term memory” of an application. Django models allow you to build complex, scalable data structures while writing pure Python, ensuring your application logic remains cleanly separated from database-specific implementation details.
Core Concepts
- Fields: Attribute types like
CharField(short text),TextField(long text), andDateTimeField. - Relationships: Using
ForeignKeyto create many-to-one relationships (e.g., many “Entries” belonging to one “Topic”). - Migrations: A version-control system for the database schema.
from django.db import models
class Topic(models.Model):
"""A topic the user is learning about."""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
"""Return a string representation of the model."""
return self.text