如何使用 managed = False 在 Django 测试期间创建 table?

How to create table during Django tests with managed = False?

来自oficial documentation

For tests involving models with managed=False, it’s up to you to ensure the correct tables are created as part of the test setup.

我不知道如何创建表格作为测试设置的一部分。我发现这个 question 并且接受的答案对我不起作用。我认为这是因为迁移文件。配置在迁移文件中,更改值 "on the fly" 没有任何效果。

在 Django 1.7+ 中有什么方法可以解决这个问题?

我觉得在Django 1.7+中应该是类似的。当您要进行 运行 测试时,您应该使用 Django 管理这些模型(仅用于测试目的)。 此转换应在创建表之前完成,Django 允许您在 settings.py

中提供 class 实例设置 TEST_RUNNER
# settings_test.py
TEST_RUNNER = 'utils.test_runner.ManagedModelTestRunner'

# test_runner.py
from django.test.runner import DiscoverRunner

class ManagedModelTestRunner(DiscoverRunner):
    """
    Test runner that automatically makes all unmanaged models in your Django
    project managed for the duration of the test run, so that one doesn't need
    to execute the SQL manually to create them.
    """  
    def setup_test_environment(self, *args, **kwargs):
        from django.db.models.loading import get_models
        super(ManagedModelTestRunner, self).setup_test_environment(*args,
                                                                   **kwargs)
        self.unmanaged_models = [m for m in get_models(only_installed=False)
                                 if not m._meta.managed]
        for m in self.unmanaged_models:
            m._meta.managed = True

    def teardown_test_environment(self, *args, **kwargs):
        super(ManagedModelTestRunner, self).teardown_test_environment(*args, **kwargs)
        # reset unmanaged models
        for m in self.unmanaged_models:
            m._meta.managed = False

我找到了一个方法。修改灯具并添加 SQL 以生成表格:

#0001_initial.py (or followings)
class Migration(migrations.Migration):

    operations = [
        migrations.RunSQL("CREATE TABLE..."),
        ...
    ]

我是 "migrations newbie",所以我不知道这是否是最佳选择。但它有效。