routers.py 1.9 KB

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