Skip to content

Instantly share code, notes, and snippets.

@EBNull
Created March 25, 2011 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EBNull/887291 to your computer and use it in GitHub Desktop.
Save EBNull/887291 to your computer and use it in GitHub Desktop.
Lets django find certain models on a certain database. Cross DB joins will still probably fail.
from django.conf import settings
#STICKY_DB_DEFAULT=None
#STICKY_DB_ALLOW_CROSS_DB_RELATIONS=False
#STICKY_DB_MODELS = {
# ('app', 'model'): 'dbalias',
# ('app', 'model'): 'dbalias',
# ('app', 'model'): 'dbalias',
#}
class StickyRouter(object):
"""A router to stick models to particular databases"""
def _find_db(self, model):
STICKY_DB_MODELS = getattr(settings, 'STICKY_DB_MODELS', {})
search = (model._meta.app_label, model.__name__)
return STICKY_DB_MODELS.get(search, getattr(settings, 'STICKY_DB_DEFAULT', None))
def db_for_read(self, model, **hints):
return self._find_db(model)
def db_for_write(self, model, **hints):
return self._find_db(model)
def allow_relation(self, obj1, obj2, **hints):
if getattr(settings, 'STICKY_DB_ALLOW_CROSS_DB_RELATIONS', False):
return True #Allow scary cross DB foreign keys
opts = [self._find_db(obj1.__class__), self._find_db(obj2.__class__)]
if opts == [None, None]:
return None #No opinion
if opts[0] == opts[1]:
return True #Both using the same DB
return False #Different DBs
def allow_syncdb(self, db, model):
opinion = self._find_db(model)
care = opinion is not None
if care and opinion == db:
return True
elif care:
return False
else:
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment