[Answer]-Django, using two databases with the same project

1👍

You can use multiple databases in django. See: https://docs.djangoproject.com/en/dev/topics/db/multi-db/#multiple-databases

But from your description, it sounds more like you just need 2 different environments. One non-production environment for accepting this virtual data, and another production environment. You can just have 2 different settings.py, and import the proper one depending on the environment.

👤Tareq

0👍

If I understand the problem well, then this is the approach I would take

1) In settings.py file (I am using mysql)

DATABASES = {
    'default':{},
    'db1': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'Database_1',
        'USER': '',
        'PASSWORD': '',


    },
    'db2':{
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'Database_2',
        'USER': '',
        'PASSWORD': '',


    }
}

2) In the urls.py file
(sample URL patterns)

urlpatterns = [
    url(r'^/login/$', views.xzy, {'database': 'db1'}),
    url(r'^com/login/$', views.xzy, {'database': 'db2'})

]

3) In xzy(request, database), you can do the following:

records = Model.objects.using(database).all()

You can use ‘database-routers’ as well. https://docs.djangoproject.com/en/dev/topics/db/multi-db/#automatic-database-routing

This should work in a simple environment. If you are using something like elasticsearch or solr, then this approach needs to modified.

Hope this helps.

Leave a comment