Models and Database
In this chapter, you will learn how to define data models using Django ORM, create database tables, and insert test data.
Why Do We Need Models?
In the previous chapter, we hardcoded the page text. A real blog needs to store multiple articles, and the content can change at any time.
Model is Django's database layer: define data structures using Python classes, and Django automatically generates the corresponding database tables.
You don't need to write a single line of SQLβthis is the core value of ORM (Object-Relational Mapping).
Defining the Post Model
Open blog/models.py and define the article model.
Example
# File path: blog/models.py
from django.db import models
from django.utils import timezone
class Category(models.Model):
"""Article category"""
name = models.CharField('Category Name', max_length=50, unique=True)
# slug is used for English identifier in URL (e.g., /category/django/)
slug = models.SlugField('URL Identifier', max_length=50, unique=True)
class Meta:
verbose_name = 'Category'
verbose_name_plural = 'Categories'
def __str__(self):
return self.name
class Post(models.Model):
"""Blog article"""
# title: CharField for short text, max_length is required
title = models.CharField('Title', max_length=200)
# slug: English identifier for the article in URL
slug = models.SlugField('URL Identifier', max_length=200, unique=True)
# summary: TextField for long text, blank=True means optional
summary = models.TextField('Summary', blank=True)
# content: TextField for unlimited length
content = models.TextField('Content')
# category: ForeignKey for one-to-many relationship, one article belongs to one category
# on_delete=models.CASCADE means when a category is deleted, all its articles are also deleted
category = models.ForeignKey(
Category,
on_delete=models.CASCADE,
verbose_name='Category',
related_name='posts' # Reverse query: category.posts.all()
)
# auto_now_add: automatically filled with current time when created
created_at = models.DateTimeField('Created At', auto_now_add=True)
# auto_now: automatically updated to current time every time it's saved
updated_at = models.DateTimeField('Updated At', auto_now=True)
class Meta:
verbose_name = 'Article'
verbose_name_plural = 'Articles'
# Default ordering: descending by creation time
ordering = ['-created_at']
def __str__(self):
# In Admin backend and Shell, display the title when showing the object
return self.title
Common Field Types Quick Reference
| Field Type | Corresponding Database Type | Use Case |
|---|---|---|
| CharField(max_length=N) | VARCHAR(N) | Short text like titles, tags, names |
YouTip