参考文档:
* https://docs.djangoproject.com/en/1.2/topics/db/multi-db/#topics-db-multi-db-routing
* http://blog.sina.com.cn/s/blog_3fbe78a60100p68a.html
目的:新项目中实现 按app实现数据库的分离
以非IC模块product为例
1. setting.py中加入
...
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'xiaofei_ecgoo', # Or path to database file if using sqlite3.
'USER': 'xiaofei', # Not used with sqlite3.
'PASSWORD': '*****', # Not used with sqlite3.
'HOST': '192.168.0.8', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '3306', # Set to empty string for default. Not used with sqlite3.
},
'product': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'xiaofei_product', # Or path to database file if using sqlite3.
'USER': 'xiaofei', # Not used with sqlite3.
'PASSWORD': '*******', # Not used with sqlite3.
'HOST': '192.168.0.8', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '3306', # Set to empty string for default. Not used with sqlite3.
}
}
...
2.增加dbrouter.py
class MyAppRouter(object):
"""A router to control all database operations on models in
the myapp application"""
def db_for_read(self, model, **hints):
"Point all operations on myapp models to 'other'"
if model._meta.app_label == 'product':
return 'product'
return None
def db_for_write(self, model, **hints):
"Point all operations on myapp models to 'other'"
if model._meta.app_label == 'product':
return 'product'
return None
def allow_relation(self, obj1, obj2, **hints):
"Allow any relation if a model in myapp is involved"
if obj1._meta.app_label == 'product' or obj2._meta.app_label == 'product':
return True
return None
def allow_syncdb(self, db, model):
"Make sure the myapp app only appears on the 'other' db"
if db == 'product':
return model._meta.app_label == 'product'
elif model._meta.app_label == 'product':
return False
return None
class MasterSlaveRouter(object):
"""A router that sets up a simple master/slave configuration"""
def db_for_read(self, model, **hints):
"Point all read operations to a random slave"
return 'default'
def db_for_write(self, model, **hints):
"Point all write operations to the master"
return 'default'
def allow_relation(self, obj1, obj2, **hints):
"Allow any relation between two objects in the db pool"
db_list = ('default','product')
if obj1._state.db in db_list and obj2._state.db in db_list:
return True
return None
def allow_syncdb(self, db, model):
"Explicitly put all models on all databases."
return True
3.配置settings.py
DATABASE_ROUTERS = ['new_ecgoo.dbrouter.MyAppRouter', 'new_ecgoo.dbrouter.MasterSlaveRouter']
注意:
写道
刚调试时,有几个页面一直报错,后发现数据库分离后,在读关联数据时,有几个写法要注意:
如:
ic = Ic.objects.filter(u__username=name)
应改为:
user = User.objects.get(username = name)
ic = Ic.objects.filter(u=user)
如:
ic = Ic.objects.filter(u__username=name)
应改为:
user = User.objects.get(username = name)
ic = Ic.objects.filter(u=user)