2013-09-24 08:27:43 +00:00
|
|
|
from django.db import DEFAULT_DB_ALIAS
|
|
|
|
|
|
|
|
|
2017-01-19 07:39:46 +00:00
|
|
|
class TestRouter:
|
2015-02-19 07:27:58 +00:00
|
|
|
"""
|
|
|
|
Vaguely behave like primary/replica, but the databases aren't assumed to
|
|
|
|
propagate changes.
|
|
|
|
"""
|
|
|
|
|
2013-09-24 08:27:43 +00:00
|
|
|
def db_for_read(self, model, instance=None, **hints):
|
|
|
|
if instance:
|
2022-02-03 19:24:19 +00:00
|
|
|
return instance._state.db or "other"
|
|
|
|
return "other"
|
2013-09-24 08:27:43 +00:00
|
|
|
|
|
|
|
def db_for_write(self, model, **hints):
|
|
|
|
return DEFAULT_DB_ALIAS
|
|
|
|
|
|
|
|
def allow_relation(self, obj1, obj2, **hints):
|
2022-02-03 19:24:19 +00:00
|
|
|
return obj1._state.db in ("default", "other") and obj2._state.db in (
|
|
|
|
"default",
|
|
|
|
"other",
|
|
|
|
)
|
2013-09-24 08:27:43 +00:00
|
|
|
|
2015-02-19 07:27:58 +00:00
|
|
|
def allow_migrate(self, db, app_label, **hints):
|
2013-09-24 08:27:43 +00:00
|
|
|
return True
|
|
|
|
|
|
|
|
|
2017-01-19 07:39:46 +00:00
|
|
|
class AuthRouter:
|
2015-02-19 07:27:58 +00:00
|
|
|
"""
|
|
|
|
Control all database operations on models in the contrib.auth application.
|
|
|
|
"""
|
2013-09-24 08:27:43 +00:00
|
|
|
|
|
|
|
def db_for_read(self, model, **hints):
|
|
|
|
"Point all read operations on auth models to 'default'"
|
2022-02-03 19:24:19 +00:00
|
|
|
if model._meta.app_label == "auth":
|
2013-09-24 08:27:43 +00:00
|
|
|
# We use default here to ensure we can tell the difference
|
|
|
|
# between a read request and a write request for Auth objects
|
2022-02-03 19:24:19 +00:00
|
|
|
return "default"
|
2013-09-24 08:27:43 +00:00
|
|
|
return None
|
|
|
|
|
|
|
|
def db_for_write(self, model, **hints):
|
|
|
|
"Point all operations on auth models to 'other'"
|
2022-02-03 19:24:19 +00:00
|
|
|
if model._meta.app_label == "auth":
|
|
|
|
return "other"
|
2013-09-24 08:27:43 +00:00
|
|
|
return None
|
|
|
|
|
|
|
|
def allow_relation(self, obj1, obj2, **hints):
|
|
|
|
"Allow any relation if a model in Auth is involved"
|
2022-02-03 19:24:19 +00:00
|
|
|
return obj1._meta.app_label == "auth" or obj2._meta.app_label == "auth" or None
|
2013-09-24 08:27:43 +00:00
|
|
|
|
2015-02-19 07:27:58 +00:00
|
|
|
def allow_migrate(self, db, app_label, **hints):
|
2013-09-24 08:27:43 +00:00
|
|
|
"Make sure the auth app only appears on the 'other' db"
|
2022-02-03 19:24:19 +00:00
|
|
|
if app_label == "auth":
|
|
|
|
return db == "other"
|
2013-09-24 08:27:43 +00:00
|
|
|
return None
|
|
|
|
|
|
|
|
|
2017-01-19 07:39:46 +00:00
|
|
|
class WriteRouter:
|
2013-09-24 08:27:43 +00:00
|
|
|
# A router that only expresses an opinion on writes
|
|
|
|
def db_for_write(self, model, **hints):
|
2022-02-03 19:24:19 +00:00
|
|
|
return "writer"
|