Skip to content

Instantly share code, notes, and snippets.

@artschwagerb
Created November 14, 2013 19:20
Show Gist options
  • Save artschwagerb/7472701 to your computer and use it in GitHub Desktop.
Save artschwagerb/7472701 to your computer and use it in GitHub Desktop.
Django Database Routers Master-Slave
import random
class MasterSlaveRouter(object):
def db_for_read(self, model, **hints):
"""
Reads go to a randomly-chosen slave.
"""
return random.choice(['master','slave1', 'slave2'])
def db_for_write(self, model, **hints):
"""
Writes always go to master.
"""
return 'master'
def allow_relation(self, obj1, obj2, **hints):
"""
Relations between objects are allowed if both objects are
in the master/slave pool.
"""
db_list = ('master', 'slave1', 'slave2')
if obj1.state.db in db_list and obj2.state.db in db_list:
return True
return None
def allow_syncdb(self, db, model):
"""
All non-auth models end up in this pool.
"""
return True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'anotherdatabase',
'USER': 'anotherusername',
'PASSWORD': 'anotherpassword',
'HOST': '192.168.1.1',
'PORT': '',
},
'master': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'anotherdatabase',
'USER': 'anotherusername',
'PASSWORD': 'anotherpassword',
'HOST': '192.168.1.1',
'PORT': '',
},
'slave1': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'anotherdatabase',
'USER': 'anotherusername',
'PASSWORD': 'anotherpassword',
'HOST': '192.168.1.2',
'PORT': '',
},
'slave2': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'anotherdatabase',
'USER': 'anotherusername',
'PASSWORD': 'anotherpassword',
'HOST': '192.168.1.3',
'PORT': '',
},
}
DATABASE_ROUTERS = ['my_project.routers.MasterSlaveRouter']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment