📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Django Framework Django Models

Django Models

6 min read Quiz at the end
Define models with field types, validators, ForeignKey, ManyToMany, and Meta options.

Django Models

from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()

class Post(models.Model):
    title       = models.CharField(max_length=255)
    slug        = models.SlugField(unique=True)
    body        = models.TextField()
    author      = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts")
    tags        = models.ManyToManyField("Tag", blank=True)
    is_draft    = models.BooleanField(default=True)
    published_at= models.DateTimeField(null=True, blank=True)
    created_at  = models.DateTimeField(auto_now_add=True)
    updated_at  = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-created_at"]
        verbose_name_plural = "posts"

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        from django.urls import reverse
        return reverse("blog:post-detail", kwargs={"slug": self.slug})
Topic Quiz · 3 questions

Test your understanding before moving on

1. Which field auto-sets time when a record is created?
💡 auto_now_add=True sets the field to current datetime only when first created.
2. What does on_delete=models.CASCADE mean?
💡 CASCADE automatically deletes related child records when parent is deleted.
3. What is the Meta class inside a model used for?
💡 class Meta defines metadata like default ordering and verbose names.