Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Models and Databases

Models and Databases

In this chapter you will learn to define data models with 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 content changes at any time.

A model is Django's database layer: use Python classes to define data structures, and Django automatically generates the corresponding database tables.

You do not need to write a single line of SQL—this is the core value of ORM (Object-Relational Mapping).


Define the Post model

Open blog/models.py, 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 the English identifier in the URL (e.g., /category/django/)

    slug

=

models.

SlugField

(

'URL identifier'

,

max_length

=

50

,

unique

=

True

)

   

class

Meta:

        verbose_name

=

'Category'

        verbose_name_plural

=

'Category'

   

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: the article's English identifier in the 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

)

   

Body: TextField with no length limit

    content

=

models.

TextField

(

'Body'

)

   

Category: ForeignKey one-to-many relationship, one article belongs to one category

   

on_delete=models.CASCADE means when a category is deleted, all articles under it are deleted as well

    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 the current time on creation

    created_at

=

models.

DateTimeField

(

'Created at'

,

auto_now_add

=

True

)

   

auto_now: automatically updated to the current time on every save

    updated_at

=

models.

DateTimeField

(

'Updated at'

,

auto_now

=

True

)

   

class

Meta:

        verbose_name

=

'Article'

        verbose_name_plural

=

'Article'

       

Sort by creation time in descending order by default

        ordering

=

[

'-created_at'

]

   

def

str

(

self

)

:

       

When displaying objects in the Admin backend and Shell, show the title

       

return

self

.

title

Common field type quick reference

Field type Corresponding database type Use Cases
CharField(max_length=N) VARCHAR(N) Short text such as titles, tags, names
TextField() TEXT Content such as article body, introduction, comments
IntegerField() INTEGER Integers such as counts, ages
DateTimeField() DATETIME Publication time, update time
ForeignKey() Foreign key constraint One-to-many relationship (article → category)
ManyToManyField() Intermediate table Many-to-many relationship (article ↔ tag)
SlugField() VARCHAR URL-friendly identifier
ImageField() VARCHAR(path) Cover image, avatar (requires the Pillow library)

__str__ The method determines how an object is displayed as a string. In the Admin backend's dropdown and Shell output, it is called to display the object name. Without this method, you will see Post object (1) such meaningless text.


Migrations: syncing models to the database

After writing the model class, you need to use a migration to create the database table.



(venv) $ python manage.py makemigrations   # 生成迁移文件(检测模型变化)

Migrations for 'blog':

  blog/migrations/0001_initial.py

    - Create model Category

    - Create model Post



(venv) $ python manage.py migrate           # 执行迁移(创建数据库表)

Operations to perform:

  Apply all migrations: admin, auth, blog, contenttypes, sessions

Running migrations:

  Applying blog.0001_initial... OK

The division of labor between the two commands:

After every modification to models.py, you must run makemigrations + migrate these two commands. Neither can be omitted: makemigrations without migrate will not create tables; migrate without makemigrations means Django does not know you changed the model.


Insert test data with Django Shell

Before starting to write pages, first use Django Shell to enter a few records into the database to verify the model works properly.



(venv) $ python manage.py shell

This opens an interactive Python Shell where you can operate on the database.

Example

Enter line by line in Django Shell

from

blog.

models

import

Category

,

Post

1. Create a category

cat_django

=

Category.

objects

.

create

(

name

=

'Django'

,

slug

=

'django'

)

cat_python

=

Category.

objects

.

create

(

name

=

'Python'

,

slug

=

'python'

)

cat_css

=

Category.

objects

.

create

(

name

=

'CSS'

,

slug

=

'css'

)

2. Create an article

Post.

objects

.

create

(

    title

=

'Complete Guide to Django Getting Started'

,

    slug

=

'django-beginner-guide'

,

    summary

=

'Learn Django from scratch, covering core concepts such as models, views, and templates.'

,

    content

=

'

Why learn Django?

Django is one of the most popular Web frameworks in Python...

'

,

    category

=

cat_django

)

Post.

objects

.

create

(

    title

=

'Python Asynchronous Programming in Detail'

,

    slug

=

'python-async'

,

    summary

=

'Understand asyncio, coroutines, and event loops in one article.'

,

    content

=

'

What is a coroutine?

A coroutine is a lighter concurrency approach than threads...

'

,

    category

=

cat_python

)

Post.

objects

.

create

(

    title

=

'CSS Grid Layout in Practice'

,

    slug

=

'css-grid-layout'

,

    summary

=

'Easily implement complex responsive layouts with CSS Grid.'

,

    content

=

'

Getting Started with Grid

Grid is a two-dimensional layout system...

'

,

    category

=

cat_css

)

3. Verify queries

print

(

Post.

objects

.

all

(

)

)

         

Output all articles

print

(

Post.

objects

.

count

(

)

)

       

Total number of articles

print

(

Post.

objects

.

filter

(

category

=

cat_django

)

)

 

Articles in the Django category


Django ORM basic queries

ORM lets you operate on the database with Python method chains, without writing SQL.

Method Equivalent SQL Return Value
Post.objects.all() SELECT * FROM blog_post QuerySet (all articles)
Post.objects.get(id=1) SELECT ... WHERE id=1 Single object (throws an exception if not found)
Post.objects.filter(category__slug='django') WHERE category.slug='django' QuerySet
Post.objects.order_by('-created_at') ORDER BY created_at DESC QuerySet
Post.objects.exclude(status='draft') WHERE status != 'draft' QuerySet

QuerySet is Lazy evaluation lazy: a defined query is not executed immediately; SQL is only sent when the data is actually needed (such as iterating, printing, or converting to a list). So you can chain multiple filters without generating multiple queries.


Hands-on: Prepare data for subsequent chapters

Enter a few more articles and categories in the Shell, covering the three categories of Django, Python, and CSS, with at least 2 articles in each category.

You can write a management command or script for batch insertion, but at this stage inserting one by one with the Shell is sufficient.


Chapter Summary

In this chapter you mastered the core workflow of Django ORM: defining Python classes (models) in models.py, generating migration files with makemigrations, syncing to the database with migrate, and inserting data using the Shell and ORM queries.

At this point, the structure of articles and categories has been established in the database.