django多数据库迁移:如何防止在每个数据库中创建django默认表
Posted
技术标签:
【中文标题】django多数据库迁移:如何防止在每个数据库中创建django默认表【英文标题】:django multiple database migrations:how to prevent to create django default tables in each database 【发布时间】:2021-07-09 20:19:59 【问题描述】:我有多个数据库,每个应用程序通过路由器类绑定到一个数据库
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 默认表的默认值 和其他 3 人各 1 个应用程序
【问题讨论】:
【参考方案1】:我终于找到了自己的答案 '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'
如果我的数据库名称与此应用名称中的默认值不匹配,这会阻止它迁移
【讨论】:
以上是关于django多数据库迁移:如何防止在每个数据库中创建django默认表的主要内容,如果未能解决你的问题,请参考以下文章