【问题标题】:How can I add a new field in model when I already have a datamigration in Django?当我已经在 Django 中进行数据迁移时,如何在模型中添加新字段?
【发布时间】:2018-05-04 20:49:35
【问题描述】:

我有一个迁移来自另一个人的工作,而且我也在使用由版本控制的代码库。我在添加新字段后创建了一个迁移文件,但问题在于之前通过函数get_or_create()创建的数据迁移(0003_datamigration_initial_service_configuration.py)在列表头部执行,而我的迁移文件数据最后我不应更改已开发的迁移。

这是我的迁移列表

  • 0001_initial.py
  • 0002_datamigration_initial_users_list.py
  • 0003_datamigration_initial_mymodel.py
  • ...
  • 0015.addnewfield

0003_datamigration_initial_mymodel.py:

from __future__ import unicode_literals

from django.db import migrations
from ..models import MyModel

def create_initial_mymodel(apps, schema_editor):
    current_product_type, created = MyModel.objects.get_or_create()
class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0002_datamigration_initial_users_list'),
    ]

    operations = [
        migrations.RunPython(create_initial_mymodel),
    ]

错误是no such column named new_field

如何在不编辑任何数据迁移的情况下解决问题?

【问题讨论】:

  • 请注意,Stack Overflow 使用 Markdown——您不需要问题中的所有 html 标签。

标签: python django python-3.x django-migrations


【解决方案1】:

您应该使用apps.get_model 来获取MyModel 模型,而不是直接导入它。

def create_initial_mymodel_forward(apps, schema_editor):
    MyModel = apps.get_model('myapp', 'MyModel')
    current_product_type, created = MyModel.objects.get_or_create()

使用apps.get_model 将加载具有正确字段的模型的历史版本。

【讨论】:

  • 我试过了,但我遇到了这样的错误:app_label, model_name = app_label.split('.') ValueError: need more than 1 value to unpack
  • 调用get_model()时需要指定app和model。
猜你喜欢
  • 2012-05-19
  • 1970-01-01
  • 2014-08-10
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 2020-04-20
  • 2017-12-08
  • 2019-06-26
相关资源
最近更新 更多