Django Models
Define database models in Python — create an Article model with fields for title, body, date, and thumbnail using Django ORM.
Django Models
Models define the structure of your database tables using Python classes. Each model maps to a single database table, and each attribute maps to a column.
Creating the Article Model
# articles/models.py
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField()
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
thumb = models.ImageField(default='default.png', blank=True)
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,
default=None
)
def __str__(self):
return self.title
Field Types
| Field | Type | Purpose |
|---|---|---|
CharField | Short text | Title, name (requires max_length) |
TextField | Long text | Article body, descriptions |
DateTimeField | Date + time | Created/updated timestamps |
SlugField | URL-safe string | URL-friendly version of the title |
ImageField | Image upload | Thumbnails, photos |
ForeignKey | Relationship | Links to another model (e.g., User) |
Field Options
title = models.CharField(max_length=100) # Required max_length
date = models.DateTimeField(auto_now_add=True) # Auto-set on creation
thumb = models.ImageField(default='default.png', blank=True) # Optional with default
author = models.ForeignKey('auth.User', on_delete=models.CASCADE) # Delete articles when user deleted
The __str__ Method
def __str__(self):
return self.title
This controls how the model appears in the admin panel and Python shell. Without it, you would see Article object (1) instead of the title.
Key Takeaways
- Models are Python classes that inherit from
models.Model - Each class attribute is a database column with a specific field type
__str__defines the display name in the admin and shell- Models must be migrated before they exist in the database