Django 简明教程

Django – Update Model

Django 的 ORM API 提供了有用的功能,用于对关系数据库中表格中存储的数据执行 CRUD 操作。

Django’s ORM API provides useful functionality for performing CRUD operations on the data stored in the tables of relational databases.

create(), update()delete() 方法在其各自已存在的表格上执行相应操作。但是,您通常需要通过添加、删除或更改模型的属性来更改模型结构本身。Django 的管理界面有助于处理这些活动。

The create(), update() and delete() methods perform their respective operations on an already existing table. However, you often need to make changes to the model structure itself, by adding, deleting or altering the attributes of the model. Django’s admin interface can be helpful in handling these activities.

The Migration System in Django

Django 有一些强大的 migration system ,用于处理模型更新过程。

Django has a powerful migration system that deals with the process of updating a model.

Django 通过迁移机制将您对模型的更改(添加字段、删除模型等)传播到数据库架构中。与迁移相关的命令使用 manage.py 脚本执行。

Django propagates the changes you make to your models (adding a field, deleting a model, etc.) into your database schema with the help Migrations mechanism. The migrations-related commands are executed with the manage.py script.

可用的命令如下 −

The following commands are available −

  1. migrate − Responsible for applying and unapplying migrations.

  2. makemigrations − Responsible for creating new migrations based on the changes made to the models.

  3. sqlmigrate − Displays the SQL statements for a migration.

  4. showmigrations − Lists a project’s migrations and their status.

首次设置 Django 项目时,它会自动安装某些应用。它们列在 settings.py 模块中的 INSTALLED_APPS 部分中。

When you first set up a Django project, it automatically installs certain apps. They are listed in the INSTALLED_APPS section in the settings.py module.

这些应用中的大多数用于管理界面中以创建和管理用户、组、授权等用途,以及与这些应用相关的数据存储在各个表中。

Most of these apps are used in the admin interface to create and manage the users, groups, authorization, etc., and the data related to these apps is stored in the respective tables.

我们需要首次运行以下 migrate command ,以创建 INSTALLED_APPS 所需的表结构 −

We need to run the following migrate command for the first time to create the table structure required for INSTALLED_APPS −

python manage.py migrate

运行上述命令将在 app package folder 中创建一个名为 migrations 的包。所有后续迁移脚本都存储在其中。

Running the above command will create a package called migrations inside the app package folder. All the subsequent migration scripts are stored in it.

随后的,当您创建新应用(使用 startapp command )时,您还需要在 INSTALLED_APPS 列表中添加它。接下来,您声明新应用所需的模型。在此,您需要创建新应用所需的数据库表。

Subsequently, when you create a new app (with startapp command), you also need to add it in the INSTALLED_APPS list. Next, you declare the models required for the new app. Here, you need to create the database tables required for the new app.

The makemigrations Command

让我们像下面这样在 models.py 模块中添加一个新模型 −

Let us add a new model in the models.py module as follows −

from django.db import models

# Create your models here.
class Dreamreal(models.Model):
   website = models.CharField(max_length=50)
   mail = models.CharField(max_length=50)
   name = models.CharField(max_length=50)
   phonenumber = models.IntegerField()

   def __str__(self):
      return "Website: {} Email: {} Name: {} Ph.: {}".format(self.website, self.mail, self.name, self.phonenumber)

   class Meta:
      db_table = "dreamreal"

要在数据库中传播新模型,请运行 makemigrations command

To propagate the new model in the database, run the makemigrations command

python manage.py makemigrations

在 migrations 文件夹中将会创建一个 migrations 脚本 0001_initial.py 。其中包含一个 Migrations class 。最初使用的 migrate command 使用这个脚本在 DATABASES 部分的 settings.py 中配置的数据库中创建一个新表 −

A migrations script 0001_initial.py will be created in the migrations folder. It contains a Migrations class. The migrate command as used initially, uses this script to create a new table in the database that has been configured in the DATABASES section of settings.py

Python manage.py migrate

最终,你决定像下面那样添加一个新的模型类,命名为 Employee

Eventually, you decide to add a new model class named Employee, as given below −

class Employee(models.Model):
   eid = models.CharField(max_length=20)
   ename = models.CharField(max_length=100)
   eemail = models.EmailField()
   econtact = models.CharField(max_length=15)
   class Meta:
      db_table = "employee"

当你再次运行 makemigrations 命令时,它将创建一个第二个 migration script

When you run the makemigrations command again, it creates the second migration script

D:\workspace\myproject> python manage.py makemigrations myapp
Migrations for 'myapp':
   myapp\migrations\0002_employee.py
   - Create model Employee

新的 migration 文件 0002_employee.py 应用 migrate 命令 −

The new migration file 0002_employee.py is applied with migrate command −

D:\workspace\myproject> python manage.py migrate
Operations to perform:
   Apply all migrations: admin, auth, contenttypes, myapp, sessions
Running migrations:
   Applying myapp.0002_employee... OK

如果你查看数据库结构,就能在其中找到 employee table

If you check in the database structure, the employee table can be found in it.

django update model

如果你觉得有必要更改任何模型的结构,则需要再次运行 migrations。

If you feel it necessary to change the structure of any of the models, you need to run the migrations again.

我们删除 email field 并添加 salary field

We drop the email field and add the salary field.

class Employee(models.Model):
   eid = models.CharField(max_length=20)
   ename = models.CharField(max_length=100)
   econtact = models.CharField(max_length=15)
   salary = models.IntegerField()
   class Meta:
      db_table = "employee"

再次运行 makemigrations 命令。

Run the makemigrations command again.

D:\workspace\myproject> python manage.py makemigrations myapp
Migrations for 'myapp':
   myapp\migrations\0003_remove_employee_eemail_employee_salary.py
      - Remove field eemail from employee
      - Add field salary to employee

The showmigrations Command

showmigrations 命令会显示迄今为止生成的迁移脚本列表,已经应用的迁移标记为 " X "。

The showmigrations command shows the list of migrations scripts generated so far, with the migrations already applied showing "X" mark.

python manage.py showmigrations
myapp
   [X] 0001_initial
   [X] 0002_employee
   [ ] 0003_remove_employee_eemail_employee_salary

再次运行 migrate command 以对 employee table 做出更改 −

Run the migrate command again to effect the changes to employee table

D:\workspace\myproject> python manage.py migrate
Operations to perform:
   Apply all migrations: admin, auth, contenttypes, myapp, sessions
Running migrations:
   Applying myapp.0003_remove_employee_eemail_employee_salary... OK

How to Roll Back the Changes?

如果你想回滚对 employee table 的最近更改并还原 0002_mployee.py 脚本的状态,

If you want to roll back the recent changes to the employee table and restore the state of 0002_mployee.py script,

D:\workspace\myproject> python manage.py migrate myapp 0002_employee
Operations to perform:
   Target specific migration: 0002_employee, from myapp
Running migrations:
   Rendering model states... DONE
   Unapplying myapp.0003_remove_employee_eemail_employee_salary... OK

返回并更改结构以确认 employee table 结构已还原。

Go back and change the structure to confirm that the employee table structure is restored.