您可以简单地将字段添加到模型并调用:
python3 manage.py makemigrations
Django 将提示您为此填写“一次性”默认值。例如,如果我在您的模型上运行它,我会看到:
You are trying to add a non-nullable field 'short_value' to metadatavalue 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: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
>>> 'default'
Migrations for 'app':
app/migrations/0002_metadatavalue_short_value.py
- Add field short_value to metadatavalue
(黑体部分是我自己写的)。
因此,此处的行将文本 default 作为值。
“一次性”值不是为您的模型指定的默认值。它只是一个存储在迁移文件中的值,并添加到可能已经存在的行中。
我们可以对迁移文件进行后期编辑,并为该列提供一个默认值,然后运行一个基本上将值从另一列复制到新列的函数,例如:
# Generated by Django 2.0.2 on 2019-02-24 19:45
from django.db import migrations, models
def copy_value_to_short_value(apps, schema_editor):
MetaDataValue = apps.get_model('app', 'metadatavalue')
db_alias = schema_editor.connection.alias
from django.db.models import F
MetaDataValue.objects.using(db_alias).all().update(
short_value=F('value')
)
class Migration(migrations.Migration):
dependencies = [
('app', '0001_initial_commit'),
]
operations = [
migrations.AddField(
model_name='metadatavalue',
name='short_value',
field=models.CharField(default='value', max_length=200, verbose_name='short_value'),
preserve_default=False,
),
migrations.RunPython(copy_value_to_short_value),
]
因此,我们定义了一个类似于 Django ORM 查询的函数 copy_value_to_short_value,然后我们将 migrations.RunPython(copy_value_to_short_value) 添加到迁移中应该完成的任务中。
您当然应该在运行迁移之前编辑迁移文件,否则迁移会出现在django_migrations 表中,并且 Django 将迁移视为“完成” ”。