首页 > 解决方案 > Django 数据迁移:表不存在

问题描述

我遇到了这里描述的问题:

Django:为初始组提供迁移

具体来说,我正在处理从 init_data 文件初始化“国家”表的遗留代码。我现在需要添加国家(例如南苏丹)。我的理解是我应该使用迁移来添加这些数据,这样 prod 数据库和测试机器就会同步。这是我尝试的迁移:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations


def forwards_func(apps, schema_editor):
    Country = apps.get_model('countries', 'Country')
    db_alias = schema_editor.connection.alias
    Country.objects.using(db_alias).update_or_create(iso='SS', defaults={'name': 'SOUTH SUDAN', 'printable_name': 'South Sudan', 'iso3': 'SSD', 'numcode': 728})


def reverse_func(apps, schema_editor):
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('countries', '__latest__'),
    ]

    operations = [
        migrations.RunPython(forwards_func, reverse_func)
    ]

新迁移适用于现有数据库,但是当测试管道启动新机器时,它会失败并显示django.db.utils.ProgrammingError: (1146, "Table 'test_cc_dev.country' doesn't exist")

我从上面的链接中了解到,问题源于需要作为一个组运行的所有迁移。我不明白解决方案。我应该在这次迁移中再次添加整个表吗?

原始数据加载到 0001_initial.py 文件中,如下所示:

def forwards_func(apps, schema_editor):
    call_command('loaddata', 'countries/fixtures/init_data')

标签: pythondjangomigration

解决方案


推荐阅读