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 ) ?
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 indjango/db/__init__.pyin theConnectionHandlerclass.Connections are not automatically removed after a query however, the connection will remain until disconnected. If there are entries in
DATABASESwhich are never used, no connection will be made to these databases.