routers.py 1.9 KB

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