45 lines
1.8 KiB
Python
45 lines
1.8 KiB
Python
# routers.py
|
|
|
|
class ProjectDatabaseRouter:
|
|
"""
|
|
A router to control all database operations on models in the
|
|
simpsons and cloudmanager applications.
|
|
"""
|
|
|
|
def db_for_read(self, model, **hints):
|
|
"""Attempts to read simpsons and cloudmanager models go to their specific dbs."""
|
|
{% for database in databases_list %}
|
|
if model._meta.app_label == '{{ database[1] }}':
|
|
return '{{ database[0] }}'
|
|
{% endfor %}
|
|
return 'default'
|
|
|
|
def db_for_write(self, model, **hints):
|
|
"""Attempts to write simpsons and cloudmanager models go to their specific dbs."""
|
|
{% for database in databases_list %}
|
|
if model._meta.app_label == '{{ database[1] }}':
|
|
return '{{ database[0] }}'
|
|
{% endfor %}
|
|
return 'default'
|
|
|
|
def allow_relation(self, obj1, obj2, **hints):
|
|
"""Allow relations if both models are in the same database."""
|
|
# Prevents accidental foreign key relationships across different physical DBs
|
|
if (
|
|
obj1._meta.app_label in {{ databases_list | map(attribute=1) | list }} or
|
|
obj2._meta.app_label in {{ databases_list | map(attribute=1) | list }}
|
|
):
|
|
return obj1._meta.app_label == obj2._meta.app_label
|
|
return None
|
|
|
|
def allow_migrate(self, db, app_label, model_name=None, **hints):
|
|
"""Ensure the app's models only show up in the designated database."""
|
|
{% for database in databases_list %}
|
|
if app_label == '{{ database[1] }}':
|
|
return db == '{{ database[0] }}'
|
|
{% endfor %}
|
|
# Ensure default Django apps (auth, sessions, etc.) don't migrate into simpsons/cloudmanager
|
|
if db in {{ databases_list | map(attribute=0) | list }}:
|
|
return False
|
|
|
|
return None |