Assign DB per model in Django using db router

When you have multiple DBs connected to django app, you might want to map some models to one db, and another to another. Imagine we want to use database X for model M1 and database Y for model M2. To do it, first, set _DATABASE attribute: class M1(models.Model): _DATABASE = "X" class M2(models.Model): _DATABASE = "Y" Now we need to create a special class, called router, which will answer to Django which DB to use, e.g. create file routers.py near settings.py: class CustomRouter(object): def db_for_read(self, model, hints): return getattr(model, "_DATABASE", "default") def db_for_write(self, model, hints): return getattr(model, "_DATABASE", "default") def allow_relation(self, obj1, obj2, **hints): """ Relations between objects are allowed if both objects are in the master/slave pool. """ db_list = ('default') return obj1._state.db in db_list and obj2._state.db in db_list def allow_migrate(self, db, model): """ All non-auth models end up in this pool. """ return True And the last thing, we need to set DATABASE_ROUTERS variable: DATABASE_ROUTERS = 'routers.CustomRouter'

#django #python
menu 0
Bruce Hardy profile picture
Oct 18, 2020
by Bruce Hardy
Did it help you?
Yes !
No

Best related

Other by Bruce Hardy