-
创建代表数据库连接的模型类:
class Database(models.Model):
name = models.CharField(max_length=256, unique=True)
config = JSONField()
-
添加label 属性以区分数据库连接实体。这里需要在django设置中设置字符串DYNAMIC_DATABASES_PREFIX和DYNAMIC_DATABASES_SEPARATOR,但也可以硬编码为一些常量:
class Database(models.Model):
...
@property
def label(self):
# We want to be able to identify the dynamic databases and apps
# So we prepend their names with a common string
prefix = getattr(settings, 'DYNAMIC_DATABASES_PREFIX', 'DYNAMIC_DATABASE')
separator = getattr(settings, 'DYNAMIC_DATABASES_SEPARATOR', '_')
return '{}{}{}'.format(prefix, separator, self.pk)
-
添加一种方法,用于将 db 连接添加到 django 的 db 连接/从中删除 db 连接(漂亮的部分是为每个 db 连接放置一个虚拟应用程序 - 这样我们可以拥有具有重复表名的不同数据库):
class Database(models.Model):
...
def register(self):
# label for the database connection and dummy app
label = self.label
# Do we have this database registered yet
if label not in connections._databases:
# Register the database
connections._databases[label] = self.config
# Break the cached version of the database dict so it'll find our new database
del connections.databases
# Have we registered our fake app that'll hold the models for this database
if label not in apps.app_configs:
# We create our own AppConfig class, because the Django one needs a path to the module that is the app.
# Our dummy app obviously doesn't have a path
AppConfig2 = type('AppConfig'.encode('utf8'),(AppConfig,),
{'path': '/tmp/{}'.format(label)})
app_config = AppConfig2(label, label)
# Manually register the app with the running Django instance
apps.app_configs[label] = app_config
apps.app_configs[label].models = {}
def unregister(self):
label = self.label
if label in apps.app_configs:
del apps.app_configs[label]
if label in apps.all_models:
del apps.all_models[label]
if label in connections._databases:
del connections._databases[label]
del connections.databases
-
通过连接名称添加连接查找,该连接还将注册到正在运行的 django 实例的连接,使其可操作:
class Database(models.Model):
...
def get_model(self, table_name):
# Ensure the database connect and it's dummy app are registered
self.register()
label = self.label
model_name = table_name.lower().replace('_', '')
# Is the model already registered with the dummy app?
if model_name not in apps.all_models[label]:
# Use the "inspectdb" management command to get the structure of the table for us.
file_obj = StringIO()
Command(stdout=file_obj).handle(database=label, table_name_filter=lambda t: t == table_name)
model_definition = file_obj.getvalue()
file_obj.close()
# Make sure that we found the table and have a model definition
loc = model_definition.find('(models.Model):')
if loc != -1:
# Ensure that the Model has a primary key.
# Django doesn't support multiple column primary keys,
# So we have to add a primary key if the inspect command didn't
if model_definition.find('primary_key', loc) == -1:
loc = model_definition.find('(', loc + 14)
model_definition = '{}primary_key=True, {}'.format(model_definition[:loc + 1], model_definition[loc + 1:])
# Ensure that the model specifies what app_label it belongs to
loc = model_definition.find('db_table = \'{}\''.format(table_name))
if loc != -1:
model_definition = '{}app_label = \'{}\'\n {}'.format(model_definition[:loc], label, model_definition[loc:])
# Register the model with Django. Sad day when we use 'exec'
exec(model_definition, globals(), locals())
# Update the list of models that the app
# has to match what Django now has for this app
apps.app_configs[label].models = apps.all_models[label]
else:
logger.info('Could not find table: %s %s', label, table_name)
else:
logger.info('Already added dynamic model: %s %s', label, table_name)
# If we have the connection, app and model. Return the model class
if (label in connections._databases and label in apps.all_models and model_name in apps.all_models[label]):
return apps.get_model(label, model_name)
-
创建自定义数据库路由,使用提到的配置字符串进行数据库选择:
class DynamicDatabasesRouter(object):
label_prefix = '{}{}'.format(
getattr(settings, 'DYNAMIC_DATABASES_PREFIX', 'DYNAMIC_DATABASE'),
getattr(settings, 'DYNAMIC_DATABASES_SEPARATOR', '_')
)
def db_for_read(self, model, **hints):
if model._meta.app_label.startswith(self.label_prefix):
# We know that our app_label matches the database connection's name
return model._meta.app_label
return None
def db_for_write(self, model, **hints):
if model._meta.app_label.startswith(self.label_prefix):
# We know that our app_label matches the database connection's name
return model._meta.app_label
return None
def allow_relation(self, obj1, obj2, **hints):
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
return None
-
在设置中注册路由器:
DATABASE_ROUTERS = ['myapp.routing.DynamicDatabasesRouter']
-
(可选)如果您使用该模型,请在管理站点中修改它:
def config(conn):
return json.dumps(conn.config)
config.short_description = 'Config'
class DatabaseAdmin(admin.ModelAdmin):
list_display = ('name', config)
admin.site.register(Database, DatabaseAdmin)