Django Multiple Database Connection And Using Them

Bhavani shanker
1 min readJul 8, 2021

adding multiple databases in Django and how to use them

settings.py file

DATABASES = {  'default': {               'ENGINE': 'django.db.backends.mysql',
'NAME': 'DB1 Name',
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
# 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
'charset': 'utf8mb4',
},
},
'social': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DB2 Name',
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
# 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
'charset': 'utf8mb4',
},
}
}

The migrate command can operate only one database at a time. By default, it operates on the default database, but by providing the — database you can tell it to synchronize other databases also. You can use “N” number of databases in Django assigning a nickname to it just like I used social name for database2.

SYNTAX: python manage.py migrate --database=[nickname/accessingname]python manage.py migrate --database=social

Accessing DataBase Manually:

If you want to access the records from the table of another database follow the steps below

SYNTAX: varname = Modelname.objects.all().using('NICKNAME OF DB')Example: Facebook.objects.all().using('social')For Saving:varname = Model.object.create(...)
varname.save(using='users')

Using Cursor:

The below code helps you to use direct SQL queries to get data from any database required

from django.db import connections
from django.http import JsonResponse
cursor = connections['social'].cursor()
cursor.execute('SELECT * FROM `handle_twitter`)
data = cursor.fetchall()
data_json=[]
header = [i[0] for i in cursor.description]
for i in data:
data_json.append(dict(zip(header, i)))
return JsonResponse(data_json)

--

--