Is it possible to change active database dynamically in Django?
For example, use one DB for inserts and updates and switch to other for readonly operations.
-
2You have multiple database connections in your settings. Have you read this? docs.djangoproject.com/en/1.3/topics/db/multi-dbS.Lott– S.Lott2011-06-29 14:22:12 +00:00Commented Jun 29, 2011 at 14:22
2 Answers
This is possible by configuring multiple databases in your settings and then using a router to specify which database configuration should be used for read and write.
Go to https://docs.djangoproject.com/en/1.3/topics/db/multi-db/#database-routers and look for "MasterSlaveRouter", which has example code for exactly what you are requesting.
Comments
It's also possible to manually select databases in queries and saves as explain in the Django Docs on multiple databases
Essentially one uses the "using" keyword argument, as in
obj.save(using='alias')
and the "using" method of the QuerySet like this:
Model.objects.using('alias').all()
alias is the name given to the database in the DATABASES item of the settings.