首先,数据库设置为master-slave(一主一备)。至于主从配置,可参考:http://www./?p=296
然后,新建一个dbrouters.py文件
- # -*- encoding=utf8 -*-
-
- 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 'slave'
-
- def db_for_write(self, model, **hints):
- """Point all write operations to the master"""
- return 'master'
-
- def allow_relation(self, obj1, obj2, **hints):
- """Allow any relation between two objects in the db pool"""
- db_list = ('master','slave')
- 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
最后修改settings.py
- ...
- DATABASES = {
- 'default': {
- 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
- 'NAME': 'dbname', # Or path to database file if using sqlite3.
- 'USER': 'username', # Not used with sqlite3.
- 'PASSWORD': 'passwd', # Not used with sqlite3.
- 'HOST': '1.1.1.1', # Set to empty string for localhost. Not used with sqlite3.
- 'PORT': '3306', # Set to empty string for default. Not used with sqlite3.
- },
- 'master': {
- 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
- 'NAME': 'dbname', # Or path to database file if using sqlite3.
- 'USER': 'username', # Not used with sqlite3.
- 'PASSWORD': 'passwd', # Not used with sqlite3.
- 'HOST': '1.1.1.1', # Set to empty string for localhost. Not used with sqlite3.
- 'PORT': '3306', # Set to empty string for default. Not used with sqlite3.
- },
- 'slave': {
- 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
- 'NAME': 'dbname', # Or path to database file if using sqlite3.
- 'USER': 'username', # Not used with sqlite3.
- 'PASSWORD': 'passwd', # Not used with sqlite3.
- 'HOST': '2.2.2.2', # Set to empty string for localhost. Not used with sqlite3.
- 'PORT': '3306', # Set to empty string for default. Not used with sqlite3.
- }
- }
-
- DATABASE_ROUTERS = ['path.dbrouters.MasterSlaveRouter']
- ...
如此,凡是涉及读操作,都会使用slave数据库;凡是写操作,都会使用master数据库。
|