-
-
Save venkatesh22/51d8efb8dca8a1b3fcd547c5a225399a to your computer and use it in GitHub Desktop.
Django Database Routers Master-Slave
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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