Created
June 22, 2026 12:33
-
-
Save EnriqueSoria/6f93591c7e304ee1a8f2b611abc0f518 to your computer and use it in GitHub Desktop.
A Django database router that defaults everything to `default` database, but allows to change it via a context manager (or decorator)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import threading | |
| from contextlib import contextmanager | |
| class DBConfig(threading.local): | |
| database_name: str = "default" | |
| DB_CONFIG = DBConfig() | |
| class OverridableDatabaseRouter: | |
| def db_for_read(self, model, **hints): | |
| return DB_CONFIG.database_name | |
| def db_for_write(self, model, **hints): | |
| return DB_CONFIG.database_name | |
| def allow_migrate(self, db, app_label, model_name=None, **hints): | |
| return db == "default" | |
| def allow_syncdb(self, db, model): | |
| return db == "default" | |
| def allow_relation(self, obj1, obj2, **hints): | |
| return None | |
| @contextmanager | |
| def force_database(database_name: str): | |
| """A context manager/decorator to temporarily set and revert the database name""" | |
| old_database_name = DB_CONFIG.database_name | |
| DB_CONFIG.database_name = database_name | |
| yield | |
| DB_CONFIG.database_name = old_database_name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment