settings.py:
DATABASES = {
‘default‘: {
‘ENGINE‘: ‘django.db.backends.mysql‘, # Add ‘postgresql_psycopg2‘, ‘mysql‘, ‘sqlite3‘ or ‘oracle‘.
‘NAME‘: ‘test‘, # Or path to database file if using sqlite3.
‘USER‘: ‘test‘, # Not used with sqlite3.
‘PASSWORD‘: ‘test‘, # Not used with sqlite3.
‘HOST‘: ‘‘, # Set to empty string for localhost. Not used with sqlite3.
‘PORT‘: ‘3306‘, # Set to empty string for default. Not used with sqlite3.
},
‘user‘: {
‘ENGINE‘: ‘django.db.backends.mysql‘, # Add ‘postgresql_psycopg2‘, ‘mysql‘, ‘sqlite3‘ or ‘oracle‘.
‘NAME‘: ‘userdb‘, # Or path to database file if using sqlite3.
‘USER‘: ‘user‘, # Not used with sqlite3.
‘PASSWORD‘: ‘user‘, # Not used with sqlite3.
‘HOST‘: ‘10.58.**.**‘, # Set to empty string for localhost. Not used with sqlite3.
‘PORT‘: ‘3306‘, # Set to empty string for default. Not used with sqlite3.
}
}
DATABASE_ROUTERS = [‘dbsettings.appdb‘]
实现自己的DB routers,这里决定了每个应用使用的是哪个DB
dbsettings.py:
class appdb(object):
def db_for_read(self, model, **hints):
#该方法定义读取时从哪一个数据库读取
return self.__app_router(model)
def db_for_write(self, model, **hints):
#该方法定义写入时从哪一个数据库读取,如果读写分离,可再额外配置
return self.__app_router(model)
def allow_relation(self, obj1, obj2, **hints):
#该方法用于判断传入的obj1和obj2是否允许关联,可用于多对多以及外键
#同一个应用同一个数据库
if obj1._meta.app_label == obj2._meta.app_label:
return True
#User和Essay是允许关联的
elif obj1._meta.app_label in (‘userApp‘,‘essayApp‘) and
#接上一行 obj2._meta.app_label in (‘userApp‘,‘essayApp‘):
return True
def allow_syncdb(self, db, model):
#该方法定义数据库是否能和名为db的数据库同步
return self.__app_router(model) == db
#添加一个私有方法用来判断模型属于哪个应用,并返回应该使用的数据库
def __app_router(self, model):
if model._meta.app_label == ‘user‘:
return ‘userdb‘
else :
return ‘default‘
使用方法
User.objects.using(‘user‘).all()
python manage.py syncdb --database=user
自定义sql:
cursor = connections[‘user’].cursor()
sql="select * user"
cursor.execute(sql)
rows = cursor.fetchall()
return render_to_response(‘index.html‘,locals())
本文出自 “水草” 博客,请务必保留此出处http://961911.blog.51cto.com/951911/1676221
原文地址:http://961911.blog.51cto.com/951911/1676221