Django 更新模型


在模型中添加字段

要在创建表后向表中添加字段,请打开models.py文件,并进行更改:

my_tennis_club/members/models.py:

from django.db import models

class Member(models.Model):
  firstname = models.CharField(max_length=255)
  lastname = models.CharField(max_length=255)
  phone = models.IntegerField()
  joined_date = models.DateField()

正如你所看到的,我们想要添加phonejoined_date到我们的会员模型。

这是模型结构的变化,因此我们必须进行迁移来告诉 Django 它必须更新数据库:

py manage.py makemigrations members

就我而言,这将导致提示,因为我尝试将不允许为空的字段添加到已包含记录的表中。

正如您所看到的,Django 询问我是否要为字段提供特定值,或者是否要停止迁移并在模型中修复它:

py manage.py makemigrations members
You are trying to add a non-nullable field 'joined_date' to members without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py
Select an option:

我将选择选项 2,然后打开models.py再次文件并允许两个新字段为 NULL 值:

my_tennis_club/members/models.py:

from django.db import models

class Member(models.Model):
  firstname = models.CharField(max_length=255)
  lastname = models.CharField(max_length=255)
  phone = models.IntegerField(null=True)
  joined_date = models.DateField(null=True)

并再次进行迁移:

py manage.py makemigrations members

这将导致这样的结果:

Migrations for 'members':
  members\migrations\0002_member_joined_date_member_phone.py
    - Add field joined_date to member
    - Add field phone to member

运行迁移命令:

py manage.py migrate

这将导致以下输出:

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, members, sessions
Running migrations:
  Applying members.0002_member_joined_date_member_phone... OK

(myworld) C:\Users\ Your Name\myworld\my_tennis_club>

插入数据

我们可以使用与之前相同的方法将数据插入到两个新字段中更新数据章节:

首先我们进入Python Shell:

py manage.py shell

现在我们在 shell 中,结果应该是这样的:

Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>

在底部,三个之后>>>编写以下内容(并按每行的 [Enter] 键):

>>> from members.models import Member
>>> x = Member.objects.all()[0]
>>> x.phone = 5551234
>>> x.joined_date = '2022-01-05'
>>> x.save()

这将在会员模型中插入电话号码和日期,至少对于第一条记录,其余四条记录暂时留空。我们将在本教程的后面部分处理它们。

执行以下命令查看 Member 表是否已更新:

>>> Member.objects.all().values()

结果应该是这样的:

<QuerySet [
{'id': 1, 'firstname': 'Emil', 'lastname': 'Refsnes', 'phone': 5551234, 'joined_date': datetime.date(2022, 1, 5)},
{'id': 2, 'firstname': 'Tobias', 'lastname': 'Refsnes', 'phone': None, 'joined_date': None},
{'id': 3, 'firstname': 'Linus', 'lastname': 'Refsnes', 'phone': None, 'joined_date': None},
{'id': 4, 'firstname': 'Lene', 'lastname': 'Refsnes', 'phone': None, 'joined_date': None},
{'id': 5, 'firstname': 'Stalikken', 'lastname': 'Refsnes', 'phone': None, 'joined_date': None}]>