Files
Django_kube/django_code/templates/routers/routers.jinja.py
T
pierre geeraert 2ba56cb00f
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 4s
new_url command will automatically gather and replace the router file
2026-07-03 23:43:37 +01:00

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