Advertisement
Guest User

Untitled

a guest
Oct 27th, 2016
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. from django.conf import settings
  2.  
  3. class DatabaseAppsRouter(object):
  4.     """
  5.     A router to control all database operations on models for different
  6.     databases.
  7.  
  8.     In case an app is not set in settings.DATABASE_APPS_MAPPING, the router
  9.     will fallback to the `default` database.
  10.  
  11.     Settings example:
  12.  
  13.     DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'}
  14.     """
  15.  
  16. def db_for_read(self, model, **hints):
  17.         """"Point all read operations to the specific database."""
  18.         if settings.DATABASE_APPS_MAPPING.has_key(model._meta.app_label):
  19.             return settings.DATABASE_APPS_MAPPING[model._meta.app_label]
  20.         return None
  21.  
  22. def db_for_write(self, model, **hints):
  23.         """Point all write operations to the specific database."""
  24.         if settings.DATABASE_APPS_MAPPING.has_key(model._meta.app_label):
  25.             return settings.DATABASE_APPS_MAPPING[model._meta.app_label]
  26.         return None
  27.  
  28. def allow_relation(self, obj1, obj2, **hints):
  29.         """Allow any relation between apps that use the same database."""
  30.         db_obj1 = settings.DATABASE_APPS_MAPPING.get(obj1._meta.app_label)
  31.         db_obj2 = settings.DATABASE_APPS_MAPPING.get(obj2._meta.app_label)
  32.         if db_obj1 and db_obj2:
  33.             if db_obj1 == db_obj2:
  34.                 return True
  35.             else:
  36.                 return False
  37.         return None
  38.  
  39. def allow_migrate(self, db, model):
  40. return True
  41.  
  42. def allow_syncdb(self, db, model):
  43.         """Make sure that apps only appear in the related database."""
  44.         if db in settings.DATABASE_APPS_MAPPING.values():
  45.             return settings.DATABASE_APPS_MAPPING.get(model._meta.app_label) == db
  46.         elif settings.DATABASE_APPS_MAPPING.has_key(model._meta.app_label):
  47.             return False
  48.         return None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement