Defining Models

A model is a Python class that maps to a database table.

Syntaxclass Post(models.Model): ...

A model defines your data. Each model is a Python class that subclasses django.db.models.Model, and each class attribute becomes a database column. Django uses this to create and manage the table for you.

By convention a Post model maps to a table named appname_post.

Example

Example Β· python
# blog/models.py
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    published = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

When to use it

  • A developer defines a BlogPost model with title, body, and published_at fields that map to database columns.
  • A team uses model __str__ to display meaningful object names in the Django admin list view.
  • A developer adds a Meta class to a model to control the default ordering of queryset results.

More examples

Define a basic model

Defines a Post model with auto-managed timestamps and a human-readable string representation.

Example Β· python
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=250)
    body = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

Model with Meta ordering

Uses the Meta inner class to set default descending ordering and a custom plural name.

Example Β· python
class Post(models.Model):
    title = models.CharField(max_length=250)
    published_at = models.DateTimeField()

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

Add a custom model method

Adds get_absolute_url() so Django admin and templates can link to the post's detail page.

Example Β· python
from django.urls import reverse

class Post(models.Model):
    title = models.CharField(max_length=250)
    slug = models.SlugField(unique=True)

    def get_absolute_url(self):
        return reverse("blog:post-detail", kwargs={"slug": self.slug})

Discussion

  • Be the first to comment on this lesson.
Defining Models β€” Django | SoundsCode