开发者

How to change database dynamically in Django?

Is it possible to change active database dynamically in Dj开发者_开发技巧ango?

For example, use one DB for inserts and updates and switch to other for readonly operations.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜