Jøê*_*èéñ 2 django django-database python-3.x
我正在尝试使用 Django 创建一个问答网站,并且我想为所有应用程序使用多个数据库
但我不想重新配置我的模型和应用程序。
我怎样才能做到这一点??
注意:论坛是实现问答网站的应用程序
我的意思是,您显然将不得不进行一些重新配置。
广义上讲,将最常用的数据库设置为默认值,将另一个数据库设置为其他数据库 - 这是根据我的生产站点中的数据库列表之一改编的。
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'databasename',
'USER': 'mydefaultuser',
'PASSWORD': 'novelpassword',
'HOST':'first-host.com',
'PORT':'3306'
},
'auth': {
'ENGINE': 'sqlserver_pymssql',
'HOST': 'myserver.com',
'NAME': 'myauthdatabase',
'PASSWORD': 'passwordhere',
'PORT': 1433,
'USER': 'username'
}}
Run Code Online (Sandbox Code Playgroud)
然后你可以在你的视图中显式使用另一个数据库,使用using:
User.objects.using('auth').all()
...或者最好,您可以使用数据库路由器更广泛地设置它:
class AuthRouter(object):
"""
A router to control all database operations on models in the
auth application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read auth models go to auth_db.
"""
if model._meta.app_label == 'auth':
return 'auth_db'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to auth_db.
"""
if model._meta.app_label == 'auth':
return 'auth_db'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the auth app is involved.
"""
if obj1._meta.app_label == 'auth' or \
obj2._meta.app_label == 'auth':
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
Make sure the auth app only appears in the 'auth_db'
database.
"""
if app_label == 'auth':
return db == 'auth_db'
return None
Run Code Online (Sandbox Code Playgroud)
添加DATABASE_ROUTERS = ['path.to.AuthRouter', 'path.to.PrimaryReplicaRouter']您的设置文件 - 这些只是从上面链接中的文档中提取的示例,但它相对简单。
我会说,除非你有一个超级清晰,简明的原因,为什么你想这样做,不这样做。您可以在单个数据库中处理所有这些,一旦您采用多数据库路线,您就会立即面临跨数据库的限制- 始终值得牢记。
| 归档时间: |
|
| 查看次数: |
1724 次 |
| 最近记录: |