I am using python(2.7),django,with mongodb.I want to create an application that support multiple databases(monogdb,oracle,Mysql,etc).Means if we select oracle on the front end the data should be save in oracle like that.Is there any way to write that app.
-
1django already supports [multiple databases](https://docs.djangoproject.com/en/1.6/topics/db/multi-db/), so what is the exact problem you are facing? – Burhan Khalid Jan 27 '14 at 10:30
-
@Burhan Khalid:Tanks for reply,Ya it supports.But i need to save in particular database when the user selects database.(if you are the owner, you are offering multiple databases to save users data),i am the user of your site and i need to save my data in oracle.Then by clicking oracle tab my data is going to be saved in oracle.This is i want.Help me if you know.Thanks in advance – Shiva Jan 27 '14 at 11:31
1 Answers
Django supports multiple databases so all you need is some code to handle switching between them.
If you have read the docs you will see that Django allows you to supply your own custom 'router' class which decides which database to use for any given query:
https://docs.djangoproject.com/en/1.6/topics/db/multi-db/#using-routers
Since you say you want to select which db "on the front end" then presumably each user of your site could choose a different database backend. This presents a problem because the db router knows nothing about the current http request and user.
I suggest you use this 'ThreadLocal' middleware to store the current request object so you can access it from your custom router:
https://github.com/jedie/django-tools/blob/master/django_tools/middlewares/ThreadLocal.py
Let's say you save the user's chosen backend in the session as request.session['db_name']
- your router would look something like this:
from django_tools.middlewares import ThreadLocal
class RequestRouter(object):
def db_for_read(self, model, **hints):
request = ThreadLocal.get_current_request()
return request.session.get('db_name', 'default')
def db_for_write(self, model, **hints):
request = ThreadLocal.get_current_request()
return request.session.get('db_name', 'default')
def allow_relation(self, obj1, obj2, **hints):
return True
def allow_syncdb(self, db, model):
return True

- 32,188
- 12
- 99
- 147