1 回答

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超18個(gè)贊
數(shù)據(jù)庫相關(guān)東西的配置主要在 settings.py 文件中完成。因此,要將多個(gè)數(shù)據(jù)庫添加到我們的 django 項(xiàng)目中,我們需要將它們添加到 DATABASES 字典中。
這些設(shè)置進(jìn)去 Settings.py
DATABASE_ROUTERS = ['path.to.DemoRouter']
DATABASE_APPS_MAPPING = {'user_data': 'users_db',
'customer_data':'customers_db'}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'users_db': {
'NAME': 'user_data',
'ENGINE': 'django.db.backends.postgresql',
'USER': 'postgres_user',
'PASSWORD': 'password'
},
'customers_db': {
'NAME': 'customer_data',
'ENGINE': 'django.db.backends.mysql',
'USER': 'mysql_cust',
'PASSWORD': 'root'
}
}
對(duì)于多個(gè)數(shù)據(jù)庫,最好談?wù)剶?shù)據(jù)庫路由器。默認(rèn)路由方案確保如果未指定數(shù)據(jù)庫,則所有查詢都回退到默認(rèn)數(shù)據(jù)庫。數(shù)據(jù)庫路由器默認(rèn)為 []。
把這個(gè)放進(jìn)去 models.py
class DemoRouter:
"""
A router to control all database operations on models in the
user application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read user models go to users_db.
"""
if model._meta.app_label == 'user_data':
return 'users_db'
elif model._meta.app_label == 'customer_data':
return 'customer_db'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write user models go to users_db.
"""
if model._meta.app_label == 'user_data':
return 'users_db'
elif model._meta.app_label == 'customer_data':
return 'customer_db'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the user app is involved.
"""
if obj1._meta.app_label == 'user_data' or \
obj2._meta.app_label == 'user_data':
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
Make sure the auth app only appears in the 'users_db'
database.
"""
if app_label == 'user_data':
return db == 'users_db'
return None
相應(yīng)的模型將被修改為
class User(models.Model):
username = models.Charfield(ax_length=100)
. . .
class Meta:
app_label = 'user_data'
class Customer(models.Model):
name = models.TextField(max_length=100)
. . .
class Meta:
app_label = 'customer_data'
使用多個(gè)數(shù)據(jù)庫時(shí),很少有有用的命令。
$ ./manage.py migrate --database=users_db
添加回答
舉報(bào)