Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple database support in django

From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.

Can anyone please tell me how one can achieve multiple database connections in Django.

Does anyone have any idea by when Django will fully/officially support Multiple database connections.

like image 668
codebreak Avatar asked Nov 06 '08 09:11

codebreak


People also ask

Can Django support multiple databases?

Django's admin doesn't have any explicit support for multiple databases. If you want to provide an admin interface for a model on a database other than that specified by your router chain, you'll need to write custom ModelAdmin classes that will direct the admin to use a specific database for content.

Which database is better for Django?

Postgresql is the preferred database for Django applications due to its open-source nature; and it's also ideal for complex queries. To optimize queries in any Django application, we will cover the following areas to perform database optimization, namely: database indexing.

Does Django support multiple column primary keys?

Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.


1 Answers

If you simply need multiple connections, you can do something like this:

from django.db import load_backend
myBackend = load_backend('postgresql_psycopg2') # or 'mysql', 'sqlite3', 'oracle'
myConnection = myBackend.DatabaseWrapper({
    'DATABASE_HOST': '192.168.1.1',
    'DATABASE_NAME': 'my_database',
    'DATABASE_OPTIONS': {},
    'DATABASE_PASSWORD': "",
    'DATABASE_PORT': "",
    'DATABASE_USER': "my_user",
    'TIME_ZONE': "America/New_York",})
# Now we can do all the standard raw sql stuff with myConnection.
myCursor = myConnection.cursor()
myCursor.execute("SELECT COUNT(1) FROM my_table;")
myCursor.fetchone()
like image 52
Dave Aaron Smith Avatar answered Sep 20 '22 07:09

Dave Aaron Smith