| 1 |
from django.db import DEFAULT_DB_ALIAS |
| 2 |
|
| 3 |
|
| 4 |
class TestRouter: |
| 5 |
""" |
| 6 |
Vaguely behave like primary/replica, but the databases aren't assumed to |
| 7 |
propagate changes. |
| 8 |
""" |
| 9 |
|
| 10 |
def db_for_read(self, model, instance=None, **hints): |
| 11 |
if instance: |
| 12 |
return instance._state.db or "other" |
| 13 |
return "other" |
| 14 |
|
| 15 |
def db_for_write(self, model, **hints): |
| 16 |
return DEFAULT_DB_ALIAS |
| 17 |
|
| 18 |
def allow_relation(self, obj1, obj2, **hints): |
| 19 |
return obj1._state.db in ("default", "other") and obj2._state.db in ( |
| 20 |
"default", |
| 21 |
"other", |
| 22 |
) |
| 23 |
|
| 24 |
def allow_migrate(self, db, app_label, **hints): |
| 25 |
return True |
| 26 |
|
| 27 |
|
| 28 |
class AuthRouter: |
| 29 |
""" |
| 30 |
Control all database operations on models in the contrib.auth application. |
| 31 |
""" |
| 32 |
|
| 33 |
def db_for_read(self, model, **hints): |
| 34 |
"Point all read operations on auth models to 'default'" |
| 35 |
if model._meta.app_label == "auth": |
| 36 |
# We use default here to ensure we can tell the difference |
| 37 |
# between a read request and a write request for Auth objects |
| 38 |
return "default" |
| 39 |
return None |
| 40 |
|
| 41 |
def db_for_write(self, model, **hints): |
| 42 |
"Point all operations on auth models to 'other'" |
| 43 |
if model._meta.app_label == "auth": |
| 44 |
return "other" |
| 45 |
return None |
| 46 |
|
| 47 |
def allow_relation(self, obj1, obj2, **hints): |
| 48 |
"Allow any relation if a model in Auth is involved" |
| 49 |
return obj1._meta.app_label == "auth" or obj2._meta.app_label == "auth" or None |
| 50 |
|
| 51 |
def allow_migrate(self, db, app_label, **hints): |
| 52 |
"Make sure the auth app only appears on the 'other' db" |
| 53 |
if app_label == "auth": |
| 54 |
return db == "other" |
| 55 |
return None |
| 56 |
|
| 57 |
|
| 58 |
class WriteRouter: |
| 59 |
# A router that only expresses an opinion on writes |
| 60 |
def db_for_write(self, model, **hints): |
| 61 |
return "writer" |