【问题标题】:Why does my Django app attempt to create migrations, when it is defined to not allow migrations in a router?当我的 Django 应用程序被定义为不允许在路由器中迁移时,为什么它会尝试创建迁移?
【发布时间】:2016-08-15 13:58:05
【问题描述】:

我有一个名为 dataapi 的 Django 应用程序,它是通过自省 PostgreSQL 数据库来编写各种模型文件(每个模式一个)而构建的。它可以工作并通过 ORM 为我们提供对所需数据的只读访问权限,但我通过模式将模型分解为多个文件,而不是将它们全部放在一个(巨大的)models.py 文件中。

我已经定义了一个ROOT/config/routers.py 文件告诉 Django 我不希望这个应用的模型使用迁移:

class DataAPIRouter(object):
    """
    A router to control all database operations on models in the
    dataapi application.
    """

    def db_for_read(self, model, **hints):
        """
        Attempts to read dataapi models go to mssqlwrds.
        """

        if model._meta.app_label == 'dataapi':
            return 'pgdata'
        return None


    def db_for_write(self, model, **hints):
        """
        Attempts to write dataapi models go to mssqlwrds.
        """

        if model._meta.app_label == 'dataapi':
            return 'pgdata'
        return None


    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the dataapi app is involved.
        """

        if obj1._meta.app_label == 'dataapi' or obj2._meta.app_label == 'dataapi':
            return True
        return None


    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Make sure the dataapi app doesn't use migrations.
        """

        if app_label == 'dataapi':
            return False
        return True

在我的设置中,我定义了路由器:

DATABASE_ROUTERS = [
    'config.routers.DataAPIRouter',
]

然而,当我使用 makemigrations 进行试运行时,它仍然显示它正在访问应用程序:

(project) [vagrant@vagrant project]$ ./manage.py makemigrations --dry-run
Migrations for 'dataapi':
  0001_initial.py:
    - Create model aco_amda
    - Create model aco_imda
    - Create model aco_indfnta
    - Create model aco_indfntq
    [...]

我错过了什么吗?我怎样才能让这个应用程序被迁移忽略?

【问题讨论】:

  • 它被忽略了。 allow_migrate 阻止在dataapi 应用程序中执行迁移。它仍然会创建迁移,这就是它的工作原理。
  • 啊,感谢您的澄清。我将发布一个 PR 来更新文档。非常感激!如果您将此作为答案提交,我会将其标记为正确。

标签: django django-models django-migrations


【解决方案1】:

事实证明,这是设计使然。正如@knbk 指出的那样,路由器中的此设置仅在您执行python manage.py migrate 时阻止迁移发生。当您运行 python manage.py makemigrations 时,它仍会创建迁移。我已向 Django 发出 PR 以在已被接受的文档中澄清这一点。

【讨论】:

  • 嘿。我刚碰到这个。那么我应该删除生成的迁移吗?如果我不删除它,该应用程序会在 migrate 命令期间显示在迁移列表中,例如Operations to perform: Apply all migrations: app_that_shouldnt_show_up, auth, contenttypes, sessions. Running migrations: Applying app_that_shouldnt_show_up.0001_initial... OK ...
  • 我已经有一段时间没有做这个了,但我相信我只是用python manage.py migrate appname --fake 伪造了它。这会将其标记为在数据库中运行而不实际运行它,IIRC。
猜你喜欢
  • 1970-01-01
  • 2020-09-25
  • 2021-02-28
  • 1970-01-01
  • 2019-06-19
  • 2012-05-23
  • 1970-01-01
  • 1970-01-01
  • 2017-08-28
相关资源
最近更新 更多