← Back to all tutorials

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

FieldTypePurpose
CharFieldShort textTitle, name (requires max_length)
TextFieldLong textArticle body, descriptions
DateTimeFieldDate + timeCreated/updated timestamps
SlugFieldURL-safe stringURL-friendly version of the title
ImageFieldImage uploadThumbnails, photos
ForeignKeyRelationshipLinks 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