Last active
August 27, 2018 14:40
-
-
Save diegogslomp/6b9b75bd76c7037818f1 to your computer and use it in GitHub Desktop.
Router to integrate django with postgres database schemas
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
class AbstractRouter(object): | |
""" | |
A router to control all database operations on models in the | |
application. | |
""" | |
def __init__(self, app, schema): | |
self.app = app | |
self.schema = schema | |
def db_for_read(self, model, **hints): | |
""" | |
Attempts to read 'app' models go to 'schema' database. | |
""" | |
if model._meta.app_label == self.app: | |
return self.schema | |
return None | |
def db_for_write(self, model, **hints): | |
""" | |
Attempts to write 'app' models go to 'schema' database. | |
""" | |
if model._meta.app_label == self.app: | |
return self.schema | |
return None | |
def allow_relation(self, obj1, obj2, **hints): | |
""" | |
Allow relations if a model in the 'app' is involved. | |
""" | |
if obj1._meta.app_label == self.app or \ | |
obj2._meta.app_label == self.app: | |
return True | |
return None | |
def allow_migrate(self, db, app_label, model=None, **hints): | |
""" | |
Make sure the 'app' only appears in the 'schema' | |
database. | |
""" | |
if app_label == self.app: | |
return db == self.schema | |
return None | |
class FooRouter(AbstractRouter): | |
def __init__(self): | |
AbstractRouter.__init__(self, 'app', 'schema') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment