Skip to content

Instantly share code, notes, and snippets.

@kaajavi
Created January 22, 2016 13:56
Show Gist options
  • Save kaajavi/c963f18a37ef854a3e47 to your computer and use it in GitHub Desktop.
Save kaajavi/c963f18a37ef854a3e47 to your computer and use it in GitHub Desktop.
Example: "How to use multiple databases django"
You can easy do this by appearing custom attribute to model:
class A(models.Model):
_DATABASE = "X"
class B(models.Model):
_DATABASE = "X"
...
Then you need to add router. Next one will select database by _DATABASE field, and models without _DATABASE attribute will select default database, also relationships will be allowed only for default database:
class CustomRouter(object):
def db_for_read(self, model, **hints):
database = getattr(model, "_DATABASE", None)
if database:
return database
else:
return "default"
def db_for_write(self, model, **hints):
database = getattr(model, "_DATABASE", None)
if database:
return database
else:
return "default"
def allow_relation(self, obj1, obj2, **hints):
"""
Relations between objects are allowed if both objects are
in the master/slave pool.
"""
db_list = ('default')
if obj1._state.db in db_list and obj2._state.db in db_list:
return True
return None
def allow_migrate(self, db, model):
"""
All non-auth models end up in this pool.
"""
return True
And the last step is specifing your router in settings.py:
DATABASE_ROUTERS = ['path.to.class.CustomRouter']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment