[英]Multiple Database Config in Django 1.2
希望這是一個簡單的問題。
我在理解Django 1.2中新的多數據庫功能的文檔時遇到了一些麻煩。 首先,我似乎找不到你如何在你的一個模型中使用第二個數據庫的例子。
當我在models.py中定義一個新類時,如何指定我打算連接哪個數據庫?
我的settings.py包含類似於 -
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'modules',
'USER': 'xxx',
'PASSWORD': 'xxx',
},
'asterisk': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'users',
'USER': 'xxxx',
'PASSWORD': 'xxxx',
}
}
編輯:我正在閱讀路由器上的文檔,如假人。 如果其他人正在努力解決這個問題,請確保在放棄之前閱讀2到3次!
是的,它有點復雜。
您可以通過多種方式實施它。 基本上,您需要某種方式來指示哪些模型與哪個數據庫相關聯。
這是我使用的代碼; 希望能幫助到你。
from django.db import connections
class DBRouter(object):
"""A router to control all database operations on models in
the contrib.auth application"""
def db_for_read(self, model, **hints):
m = model.__module__.split('.')
try:
d = m[-1]
if d in connections:
return d
except IndexError:
pass
return None
def db_for_write(self, model, **hints):
m = model.__module__.split('.')
try:
d = m[-1]
if d in connections:
return d
except IndexError:
pass
return None
def allow_syncdb(self, db, model):
"Make sure syncdb doesn't run on anything but default"
if model._meta.app_label == 'myapp':
return False
elif db == 'default':
return True
return None
這種方式的工作方式是我創建一個文件,其中包含要使用的數據庫名稱以保存我的模型。 在您的情況下,您將創建一個名為asterisk.py
的單獨models
樣式文件,該文件與應用程序的模型位於同一文件夾中。
在models.py
文件中,您將添加
from asterisk import *
然后,當您實際從該模型請求記錄時,它的工作方式如下:
records = MyModel.object.all()
MyModel
模塊是myapp.asterisk
如果你想對每個模型的數據庫選擇進行控制,那么這樣的東西就可以了:
from django.db import connections
class DBRouter(object):
"""A router to control all database operations on models in
the contrib.auth application"""
def db_for_read(self, model, **hints):
if hasattr(model,'connection_name'):
return model.connection_name
return None
def db_for_write(self, model, **hints):
if hasattr(model,'connection_name'):
return model.connection_name
return None
def allow_syncdb(self, db, model):
if hasattr(model,'connection_name'):
return model.connection_name
return None
然后為每個模型:
class MyModel(models.Model):
connection_name="asterisk"
#etc...
請注意,我還沒有測試過第二個選項。
Jordans的附錄回答如上。 對於第二個選項,allow_syncdb方法正常工作如下:
def allow_syncdb(self, db, model):
if hasattr(model,'connection_name'):
return model.connection_name == db
return db == 'default'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.