DhruvPathak
DhruvPathak

Reputation: 43235

Django multiple databases, does Django connect to all of them initially?

Sample database configuration for MySQL :

DATABASES = {
    'auth_db': {
        'NAME': 'auth_db',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'swordfish',
    },
    'master': {
        'NAME': 'master',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'spam',
    },
    'slave1': {
        'NAME': 'slave1',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'eggs',
    },
    'slave2': {
        'NAME': 'slave2',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'bacon',
    },
}

Does Django connect to all of them initially, even if some of the databases are not used at all ? eg.

Using raw cursors with multiple databases

If you are using more than one database you can use django.db.connections to obtain the connection (and cursor) for a specific database. django.db.connections is a dictionary-like object that allows you to retrieve a specific connection using its alias:

from django.db import connections

cursor = connections['my_db_alias'].cursor()

So here, 1. the connections object contains already made connections ? Or does it connect when a request for cursor is made ? 2. Is there a way to change this default behaviour and have the connections made on demand, ( All of the querying is as raw querying, and all databases are MySQL ) ?

Upvotes: 5

Views: 2395

Answers (2)

Austin Phillips
Austin Phillips

Reputation: 15746

A persistent connection will be made to the requested database on the first access using django.db.connections. That is, connections are lazily evaluated and connected only on first use. The relevant code is in django/db/__init__.py in the ConnectionHandler class.

Connections are not automatically removed after a query however, the connection will remain until disconnected. If there are entries in DATABASES which are never used, no connection will be made to these databases.

Upvotes: 6

Guddu
Guddu

Reputation: 1588

Django uses the database with the alias of default when no other database has been selected. If you don’t have a default database, you need to be careful to always specify the database that you want to use. In your case, you don't need a default or a auth_db for user auth etc?

In any case, connections should be on-demand , you could connect to the MYSQL Explorer and issue the following command to see the active connections and then request a cursor and check the result of the command again and compare. The command is as below...

SHOW PROCESSLIST

http://dev.mysql.com/doc/refman/5.1/en/show-processlist.html

Please report back your findings.

Upvotes: -1

Related Questions