python - Django Rest Framework 多个数据库
问题描述
我是 Django 新手,我正在尝试了解 Django 如何为我的应用程序使用两个数据库。
数据库 1 - 我想用于 Django 系统
数据库 2 是一个包含数据的现有数据库,我想让这些数据在我的 Django API 中可用,如下图所示:
谢谢大家
解决方案
我用 DRF 和 django 来做这个。 使用数据库路由器
这是我的路由器,其中不同数据库的每组模型都转到不同的文件。
class DatabaseRouter(object):
def module_switch(self,model):
result = 'default'
if model.__module__.endswith('foo_db1_models'): result = 'foo'
if model.__module__.endswith('bar_db2_models'): result = 'bar'
if model.__module__.endswith('baz_models'): result = 'baz'
if model.__module__.endswith('grid_models'): result = 'grid'
#print 'here', model.__module__, result, model.__class__.__name__
return result
def db_for_read(self, model, **hints):
return self.module_switch(model)
def db_for_write(self, model, **hints):
return self.module_switch(model)
def allow_relation(self, obj1, obj2, **hints):
"""
Relations between objects are allowed if both objects are
in the master/slave pool.
"""
# db_list = ('master', 'slave1', 'slave2')
# if obj1._state.db in db_list and obj2._state.db in db_list:
# return True
return None
def allow_migrate(self, db, app_label, model_name, **hints):
"""
All non-auth models end up in this pool.
"""
return True
在 settings.py 中,您指定路由器:
DATABASE_ROUTERS = ['my_proj_foo.db_router.DatabaseRouter']
和其他数据库:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db'
'USER': 'foo',
'PASSWORD': 'bar',
'HOST': 'db.example.com',
'PORT': '3306'
},
'bar': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'bar'
'USER': 'foo',
'PASSWORD': 'bar',
'HOST': 'bar.example.com',
'PORT': '3306'
},
'baz': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'baz',
'USER': 'foo',
'PASSWORD': 'bar',
'HOST': 'baz.example.com',
'PORT': '5432'
},
},
推荐阅读
- c# - 如何在 Blazor Signalr 的多个窗口中刷新同一登录用户的数据
- apache-spark - 覆盆子上的 spark-shell,4 次尝试中的 1 次尝试从另一个开始我收到各种错误消息
- java - 将spring boot war文件部署到外部tomcat
- r - 我怎样才能得到一系列数字作为我的答案,*不仅是最后一个数字
- git - 视觉工作室 + Git
- asp.net-mvc - Asp.Net Core 5.0 中带有 cookie 的电子商务用户存储桶系统
- python - 如果将参数传递给类,如何抛出自定义异常
- java - 我正在处理注册登记。我正在努力使用以下方法 RemoveMember()
- c - 使用非常规的 for 循环更高效的 Asm?
- angular - 如何创建实现行突出显示行选择的角度基表(或行)组件?