Created
September 30, 2017 05:53
-
-
Save houming818/b7b2381b19be8061f2942d9f0d901a68 to your computer and use it in GitHub Desktop.
DBRouter class for django
This file contains hidden or 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 DBRouter(object): | |
""" | |
A router to control all database operations on models in the auth application. | |
""" | |
def db_for_read(self, model, **hints): | |
""" | |
Attempts to read auth models go to auth_db. | |
""" | |
if model._meta.app_label in settings.DATABASES.keys(): | |
return model._meta.app_label | |
return 'default' | |
def db_for_write(self, model, **hints): | |
""" | |
Attempts to write auth models go to auth_db. | |
""" | |
if model._meta.app_label in settings.DATABASES.keys(): | |
return model._meta.app_label | |
return 'default' | |
def allow_relation(self, obj1, obj2, **hints): | |
""" | |
Allow relations if a model in the auth app is involved. | |
""" | |
if obj1._meta.app_label in settings.DATABASES.keys(): | |
db_obj1 = obj1._meta.app_label | |
else: | |
db_obj1 = 'default' | |
if obj2._meta.app_label in settings.DATABASES.keys(): | |
db_obj2 = obj2._meta.app_label | |
else: | |
db_obj2 = 'default' | |
if db_obj1 == db_obj2: | |
return True | |
return False | |
def allow_migrate(self, db, app_label, model_name=None, **hints): | |
""" | |
Make sure the auth app only appears in the 'auth_db' database. | |
""" | |
app_db = "default" | |
if app_label in settings.DATABASES.keys(): | |
app_db = app_label | |
return app_db == db |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment