定义模型类
将 Python 类转换为数据库表
定义模型类 是 CoddyKit 上的免费 Django Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Django Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Django Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
A Class That Becomes a Table
In Django, a model is a Python class that describes one kind of data. Each model becomes a real database table for you.
Inherit from models.Model
Every model subclasses models.Model. That parent gives your class all the powers to talk to the database. 🗄️
from django.db import models
class Book(models.Model):
passFields Are Class Attributes
You describe columns by adding fields as class attributes. Each field is one column in the table Django will build.
class Book(models.Model):
title = models.CharField(max_length=200)One Field, One Column
Think of it simply: one field maps to one column. Add a field and you add a column to the table.
class Book(models.Model):
title = models.CharField(max_length=200)
pages = models.IntegerField()Models Live in models.py
You write your models inside each app's models.py file. Django knows to look there for the data shapes of that app.
The Automatic Primary Key
Django quietly adds an id field as the primary key. You get a unique identifier for every row without writing any code.
No SQL Required
You never write CREATE TABLE by hand. The ORM turns your Python class into SQL, so you stay in Python the whole time.
Class Name to Table Name
By default the table name is the app label plus the lowercased class name, like app_book. Django picks a sensible name for you.
Instances Are Rows
Each instance of your model is one row of data. Create a Book object and you are describing one book record.
book = Book(title="Dune", pages=412)Singular, CapitalizedNames
Name models in singular CamelCase: use Book, not Books. Django adds plurals where it needs them in the admin.
Migrations Make It Real
A model is just a plan until you run migrations. That step creates the matching table inside your real database.
Quick Check
Let's confirm what a Django model actually maps to.
Recap: Models in a Nutshell
You learned that a model is a class extending models.Model, its fields become columns, and migrations turn it into a real table. Nice start! 🎉
常见问题解答
「定义模型类」课时是免费的吗?
是的 — 「定义模型类」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Django Academy 课程的其余内容,请升级到 CoddyKit PRO。 Django Academy 课程共包含 4 节课。
「定义模型类」这节课中我会学到什么?
将 Python 类转换为数据库表 你通过在浏览器中直接运行的动手代码来练习 Django Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Django Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Django Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「定义模型类」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Django Academy 课中编写并运行代码吗?
能。每节 Django Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。