在迁移fi中使用特定模型时,Django测试失败

2024-09-28 01:33:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我为特定的Django 1.11应用程序手动创建了一个数据迁移文件:

from __future__ import unicode_literals
from django.db import migrations, models

def set_item_things(apps, schema_editor):
    MyModel = apps.get_model('my_app', 'MyModel')
    # NOTE: if I remove this line then the tests will work
    MyOtherModel = apps.get_model('my_other_app', 'MyOtherModel')

    for item in MyModel.objects.all():
        # NOTE: if I remove this line then the tests will work
        thingy = MyOtherModel.get(example_field=item.color) 
        item.other_thing = thingy
        item.save()

class Migration(migrations.Migration):
    dependencies = [
        ('contracts', '0014_my_previous_migration'),
    ]

    operations = [
        migrations.RunPython(set_item_things),
    ]

当我运行python manage.py migrate时,一切正常。
但每当我使用pytest运行测试时,我会得到以下信息:

^{pr2}$

所以看起来app config没有正确配置,这已经很奇怪了,因为migrate命令运行得很顺利。在

总之:这是my_other_app/apps.py的内容:

from django.apps import AppConfig

class MyOtherAppConfig(AppConfig):
    name = 'my_other_app'

基本上与其他应用程序目录中的apps.py非常相似,当然除了名字。在

不管是什么原因,我认为我的配置不应该正确。在

唯一的修复方法是从迁移文件中删除对my_other_app的任何引用。在

我已经尝试将此添加到my_other_apps/__init__.py

default_app_config = 'my_other_apps.apps.MyOtherAppConfig'

但一切都没有改变。在

我已经尝试过查看my_other_apps/models.py中是否存在循环依赖,但似乎并非如此。在

我错过了什么?在


Tags: apps文件djangofrompyimportapp应用程序
2条回答

我发现类似的SO question:MyOtherModel来自不同的应用程序,因此在迁移文件中,我必须将应用程序上次迁移指定为附加依赖项,即:

class Migration(migrations.Migration):
    dependencies = [
        ('contracts', '0014_my_previous_migration'),
        # THIS extra line solves the problem!
        ('my_other_app', '002_my_last_migration'),
    ]

    operations = [
        migrations.RunPython(set_item_things),
    ]

您不应该在迁移文件中接触来自其他应用程序的模型,除非您为其他应用程序的迁移指定适当的依赖关系。基本上,如果您想使用MyOtherModelfrommy_other_app,那么您必须在迁移中向{}添加条目,以指向my_other_app中的迁移,其中{}存在并且处于所需状态。在

“Exists”和“desired state”在这里需要一些解释:当Django处理迁移时,它不会检查应用程序的models.py中的实际模型状态,而是尝试从创建迁移时的时间点复制模型。因此,如果您想使用some_field,但该字段是在以后的迁移中添加的,那么至少必须指向引入该字段的迁移。在

同样,若稍后删除了字段,则依赖项必须指向迁移之前的某个迁移。在

请参见Django文档中的Migrating data between third-party apps。在

相关问题 更多 >

    热门问题