查看以Django

时间:2018-05-05 03:17:55

标签: python django django-migrations

使用Django 1.11,我试图添加一个以其他列为条件的新列(如下图所示)并在前端查看。这个link是最接近的例子,但我想在Django中实现它。我们怎么做到这一点?

enter image description here

1 个答案:

答案 0 :(得分:3)

我建议在迁移文件上实施此操作:

  1. 更改模型后,执行./manage.py makemigrations

  2. 在编辑器中打开新的迁移文件,该文件的内容可能类似如下:

    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)),
        ]
    
  3. 现在,您必须使用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),
        ]
    
  4. 运行./manage.py migrate

  5. 详细了解Django migrations