使用Django 1.11,我试图添加一个以其他列为条件的新列(如下图所示)并在前端查看。这个link是最接近的例子,但我想在Django中实现它。我们怎么做到这一点?
答案 0 :(得分:3)
我建议在迁移文件上实施此操作:
更改模型后,执行./manage.py makemigrations
在编辑器中打开新的迁移文件,该文件的内容可能类似如下:
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [('migrations', '0001_initial')]
operations = [
migrations.AddField('MyModel', 'A_islargerthan_B', models.BooleanField(default=False)),
]
现在,您必须使用migrations.RunPython
注入更新程序代码:
from django.db import migrations, models
def update_A_islargerthan_B(apps, schema_editor):
MyModel = apps.get_model('my_app', 'MyModel')
for obj in MyModel.objects.all():
obj.A_islargerthan_B = obj.column_A > obj.column_B
obj.save()
class Migration(migrations.Migration):
dependencies = [('migrations', '0001_initial')]
operations = [
migrations.AddField('MyModel', 'A_islargerthan_B', models.BooleanField(default=False)),
migrations.RunPython(update_A_islargerthan_B),
]
运行./manage.py migrate