Skip to content

Instantly share code, notes, and snippets.

@ashchristopher
Created December 27, 2014 04:33
Show Gist options
  • Save ashchristopher/3de6caa1f8d3f8247466 to your computer and use it in GitHub Desktop.
Save ashchristopher/3de6caa1f8d3f8247466 to your computer and use it in GitHub Desktop.
base db router
class BaseRouter(object):
"""
Base class for routers allowing several apps to be grouped in a shard group.
Subclasses need to define a list of app names and a prefix for the db names of the shard group.
e.g.,
app_list = ('my_app1', )
db_names_prefix = 'my_shard_'
"""
app_list = tuple()
db_name_prefix = None
def db_for_read(self, model, **hints):
if model._meta.app_label in self.app_list:
instance = hints.get('instance')
if instance:
return instance.get_shard()
return None
def db_for_write(self, model, **hints):
if model._meta.app_label in self.app_list:
instance = hints.get('instance')
if instance:
return instance.get_shard()
return None
def allow_syncdb(self, db, model):
if model._meta.app_label in ['south']:
return True
# This logic was pulled from: https://github.com/malcolmt/django-multidb-patterns/blob/master/sharding/reviews/router.py#L22
# and is correct, but very ugly.
this_app = (model._meta.app_label in self.app_list)
_db = db.startswith(self.db_names_prefix)
if this_app:
return _db
if _db:
return False
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment