Detailed explanation of django Model model layer

As the "brain center interface" of the Django framework, the Model layer is the bridge connecting business logic Python code and relational-database data. Today we will use a clear practical route to learn the core knowledge points of Django ORM and Model~


Course Objectives

  1. Understand the positioning and value of django ORM
  2. Master the basic definition syntax and field types of Model
  3. Proficient in database migration (from creating tables to maintaining table structures)
  4. Learn to use QuerySet to complete CRUD and common queries

Introduction to django ORM

ORM (Object-Relational Mapping) is not unique to Django, but it is one of the "most development efficient" modules in the Django ecosystem:

  • It maps database tables to Python classes (Model we wrote)
  • Map a record in the table to an instance of the class
  • Encapsulate SQL's addition, deletion, modification, query, filtering, sorting, etc. into Python method/attribute calls

Why should we use it?

AdvantagesSpecific instructions
Cross-database compatibilityOne set of code can almost seamlessly switch to mainstream relational-databases such as SQLite/MySQL/PostgreSQL/Oracle
Anti-SQL injectionAll query conditions entered by users will be automatically escaped by Django, eliminating the need to manually deal with security risks
Python nativeUse the familiar syntax of Python classes, attributes, methods, and chain calls to write logic without having to remember complex SQL
High maintainabilityBusiness logic and data structure definitions are all in Python files, without scattered SQL, which facilitates version control and modification

Definition of Model

Model class must be written in django applicationmodels.pyfile, and ** must inherit fromdjango.db.models.Model**。

The first complete Model

Let's first write an Article Management Model, covering basic fields, common field options,__str__method andMetakind:

from django.db import models
from django.utils import timezone  # 推荐用django内置的时区处理工具


class Article(models.Model):
    # 字段定义(通用字段选项放在参数里)
    title = models.CharField(
        max_length=200,  # CharField必须加的必填项
        null=False,       # 数据库层面不允许为NULL
        blank=False,      # 表单验证层面不允许为空(和null配合使用更严谨)
        help_text="文章标题(最多200字)"  # 后台/admin/表单会显示的提示文本
    )
    content = models.TextField(help_text="文章正文内容")
    pub_date = models.DateTimeField(
        "发布时间",  # 可选的第一参数,指定字段在后台/admin的显示名
        default=timezone.now  # 默认值设为当前时间
    )
    author = models.CharField(max_length=100)
    views = models.IntegerField(default=0, help_text="文章阅读量")

    # __str__方法:定义实例在Python终端、后台/admin的显示文本
    def __str__(self):
        return f"《{self.title}》 - {self.author}"

    # Meta类:定义Model的「元数据」(表名、排序、后台显示名等)
    class Meta:
        ordering = ["-pub_date"]  # 默认按发布时间倒序排列(减号表示倒序)
        verbose_name = "文章"       # 后台/admin显示的单数名
        verbose_name_plural = "文章"  # 后台/admin显示的复数名(中文一般单数复数一致)

High frequency common field types

Django has built-in dozens of field types, covering most development scenarios. Here are the most commonly used ones:

Field typeApplicable scenariosPrecautions
CharFieldShort text (title, name, email prefix)Must be specifiedmax_length
TextFieldLong text (article text, comments, description)No need to specify the length
IntegerFieldInteger (age, quantity, ID)can also be usedPositiveIntegerFieldLimit positive integers
DecimalFieldDecimal amounts and high precision requirementsMust be specifiedmax_digits(total number of digits) anddecimal_places(number of decimal places)
DateTimeFieldDate and time (release time, creation time)Matchauto_now_add(set automatically on creation) orauto_now(Automatically set when modifying) Very easy to use
BooleanFieldBoolean value (whether to publish, whether to stick to the top)The default value can be setTrueorFalse
ForeignKeyMany-to-one relationship (one article corresponds to one author)Must be specifiedto(associated Model) andon_delete(Strategy for deleting associated data)
ManyToManyFieldMany-to-many relationship (one article corresponds to multiple tags)No need to specifyon_delete, the deletion strategy is automatically handled by django

Database migration

The Model class is just a "data structure description" at the Python level. To actually turn it into a table in the database, a Migration operation must be performed.

Two-step core process of migration

1. Generate migration file (makemigrations

This step will detectmodels.pychanges** and generate a Python script file (stored in the corresponding applicationmigrationsfolder), this script is "reversible", so you don't have to worry about changing the table structure.

# 生成所有应用的迁移文件
python manage.py makemigrations

# 生成指定应用的迁移文件(推荐,更精准)
python manage.py makemigrations blog  # 假设你的应用叫blog

2. Execute migration (migrate

This step will read the migration file and translate it into SQL statements to actually create/modify/delete tables in the database.

# 执行所有未应用的迁移
python manage.py migrate

# 执行指定应用的迁移
python manage.py migrate blog

Commonly used migration auxiliary commands

Check migration status

# 查看所有应用的迁移文件状态([X]表示已应用,[ ]表示未应用)
python manage.py showmigrations

# 查看指定应用的迁移状态
python manage.py showmigrations blog

Rollback migration

# 回滚到指定的迁移版本(比如blog应用的0001_initial)
python manage.py migrate blog 0001_initial

# 回滚到迁移前的状态(删除该应用的所有表)
python manage.py migrate blog zero

Basic operations of QuerySet

Model classobjectsThe attribute is the Manager automatically generated by Django. All database operations must be called through it. The returned result is a QuerySet (which can be understood as a "delayed execution query set". The database will only be checked when the data is actually used, and the performance is very high).

Create record (Create)

Method 1:save()

Instantiate the Model class first and then call it manuallysave()This method is suitable for scenarios where instance attributes need to be modified and then saved.

from blog.models import Article
from django.utils import timezone

# 1. 实例化
article = Article(
    title="django Model入门教程",
    content="今天我们来学习django的Model层...",
    author="张三",
    pub_date=timezone.now()
)
# 2. 手动修改属性(可选)
article.views = 10
# 3. 保存到数据库
article.save()

Method 2:create()

directly through the managercreate()The method is created and saved, which is suitable for scenarios where no additional modification of attributes is required, and the code is more concise.

Article.objects.create(
    title="django ORM的优势",
    content="django ORM有跨数据库兼容、防SQL注入等优势...",
    author="李四"
)

Query records (Retrieve)

Get all records

# 返回所有Article的QuerySet
all_articles = Article.objects.all()

Get a single record

Notice:get()The method must return ** and can only return one record **. If there is none or multiple records, an exception will be thrown.

# 用主键id查询(最常用)
article = Article.objects.get(id=1)

# 用其他唯一字段查询(比如unique=True的slug)
# article = Article.objects.get(slug="django-model-intro")

Get the first/last record

# 按默认排序(Meta里的ordering)取第一条
first_article = Article.objects.first()

# 按默认排序取最后一条
last_article = Article.objects.last()

Filter query (filter()

filter()The method returns a QuerySet of multiple records that meet the conditions and supports chain calls.

# 查询作者是张三的文章
zhang_articles = Article.objects.filter(author="张三")

# 查询2024年发布的文章(双下划线__表示字段查询操作)
2024_articles = Article.objects.filter(pub_date__year=2024)

# 链式调用:查询2024年发布、作者是张三的文章
zhang_2024_articles = Article.objects.filter(author="张三").filter(pub_date__year=2024)

Update records (Update)

Update a single record

andsave()The process of creating records is similar. First query the instance, modify the attributes, and thensave()

article = Article.objects.get(id=1)
# 修改属性
article.title = "django Model入门教程(升级版)"
article.views += 1  # 阅读量加1
# 保存
article.save()

Batch update

pass directlyfilter()+update()This method does not require querying the instance first, is more efficient, and is suitable for modifying a large number of records that meet the conditions.

# 把所有作者是张三的文章的阅读量加100
Article.objects.filter(author="张三").update(views=models.F("views") + 100)
# 注意:批量更新不能用普通的Python变量,要用models.F()来引用数据库里的字段值

Delete record (Delete)

Delete a single record

Query the instance first and then calldelete()method.

article = Article.objects.get(id=1)
article.delete()

Batch delete

pass directlyfilter()+delete()Method, does not need to query the instance first, and is more efficient.

# 删除所有2022年之前发布的文章
Article.objects.filter(pub_date__lt="2022-01-01").delete()

Course Summary

Today we started with the positioning of ORM and learned:

  1. How to define a complete django Model using Python classes
  2. Frequently used field types and common field options
  3. Two-step core process and auxiliary commands for database migration
  4. Basic CRUD operations of QuerySet (create, query, update, delete)

These are the core foundation of Django development. After mastering them, we can further learn about Model relationships, advanced queries, performance optimization, etc. ~