django多数据库迁移:如何防止在每个数据库中创建django默认表

dzjeubhm  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(391)

我有多个数据库,每个应用程序通过路由器类绑定到一个数据库

class DatabaseRouter:
    """
    A router to control all database operations on models in the
    auth and contenttypes applications.
    """
    lawyer_app_labels = {'lawyer'}
    court_app_labels = {'court'}
    type_app_labels = {'type'}

    def db_for_read(self, model,**hints):
        """
        Attempts to read auth and contenttypes models go to auth_db.
        """
        if model._meta.app_label in self.lawyer_app_labels:
            return 'lawyer_db'
        if model._meta.app_label in self.court_app_labels:
            return 'court_db'
        if model._meta.app_label in self.type_app_labels:
            return 'type_db'
        return None

    def db_for_write(self, model,**hints):
        """
        Attempts to write auth and contenttypes models go to auth_db.
        """
        if model._meta.app_label in self.lawyer_app_labels:
            return 'lawyer_db'
        if model._meta.app_label in self.court_app_labels:
            return 'court_db'
        if model._meta.app_label in self.type_app_labels:
            return 'type_db'
        return None

    def allow_relation(self, obj1, obj2,**hints):
        """
        Allow relations if a model in the auth or contenttypes apps is
        involved.
        """
        if (
                obj1._meta.app_label in self.lawyer_app_labels or
                obj2._meta.app_label in self.lawyer_app_labels
        ):
            return True

        if (
                obj1._meta.app_label in self.court_app_labels or
                obj2._meta.app_label in self.court_app_labels
        ):
            return True

        if (
                obj1._meta.app_label in self.type_app_labels or
                obj2._meta.app_label in self.type_app_labels
        ):
            return True

        return None

    def allow_migrate(self, db, app_label, model_name=None,**hints):
        """
        Make sure the auth and contenttypes apps only appear in the
        'auth_db' database.
        """
        if app_label in self.lawyer_app_labels:
            return db == 'lawyer_db'
        if app_label in self.court_app_labels:
            return db == 'court_db'
        if app_label in self.type_app_labels:
            return db == 'type_db'
        return None

每次尝试使用--database标志进行迁移时,它都会成功创建应用程序表,但在所有应用程序django中都会创建默认表,例如会话和内容类型。如何防止在设置设置中有4个数据库正确设置django默认表的默认值,以及为1个应用程序分别设置3个其他数据库

mu0hgdu0

mu0hgdu01#

我终于找到了自己的答案{'admin','auth','contenttypes','sessions'}这是django默认应用程序的名称,所以我把它们包括在

base_app_labels = { 'admin', 'auth',  'contenttypes', 'sessions' }
def allow_migrate(self, db, app_label, model_name=None,**hints):
    if app_label in self.base_app_labels:
        return db == 'default'

如果my db name与此应用程序名称中的默认值不匹配,则会阻止其迁移

相关问题