Created
March 25, 2011 18:08
-
-
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.
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
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