Django, a popular Python web framework, provides excellent support for working with databases. By default, Django supports connecting to a single database, but there are scenarios where you may need to connect multiple databases to your Django project. In this blog post, we will explore how to establish connections to multiple databases and perform database operations seamlessly in Django.
Configuring Multiple Databases:
To connect multiple databases in Django, you need to define their configurations in your project's settings file (settings.py). Within the settings file, locate the DATABASES dictionary, which holds the database configurations. By default, it contains a single entry named 'default'. To add more databases, you can define additional entries with unique names. For example:
`DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'default_db',
'USER': 'your_username',
'PASSWORD': 'your_password',
'HOST': 'localhost',
'PORT': '3306',
},
'second_db': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'second_db',
'USER': 'your_username',
'PASSWORD': 'your_password',
'HOST': 'localhost',
'PORT': '5432',
},
}`
In the above example, we added a second entry named 'second_db' with its respective configuration parameters. Adjust the values according to your specific databases.
Database Routing:
After configuring the databases, Django needs to know which database to use for different models or database operations. Django provides a feature called database routing that allows you to specify the database to use based on certain conditions. To configure database routing, you need to create a new Python module in your project (e.g., database_router.py) and define the routing logic.
class DatabaseRouter:
def db_for_read(self, model, **hints):
if model._meta.app_label == 'app_label':
return 'second_db'
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == 'app_label':
return 'second_db'
return None
def allow_relation(self, obj1, obj2, **hints):
if obj1._meta.app_label == 'app_label' or obj2._meta.app_label == 'app_label':
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
if app_label == 'app_label':
return db == 'second_db'
return None
In the above example, we check if the model belongs to the specified app label and return the name of the database. You can customize this logic based on your project's requirements.
Using Multiple Databases:
Now that you have configured the databases and created the routing logic, you can start using multiple databases in your Django project. To perform database operations on a specific database, you can use the using keyword argument with Django's database-related functions. For example:
from django.db import connections
def fetch_data_from_multiple_databases():
default_db_cursor = connections['default'].cursor()
second_db_cursor = connections['second_db'].cursor()
default_db_cursor.execute('SELECT * FROM table_name')
default_data = default_db_cursor.fetchall()
second_db_cursor.execute('SELECT * FROM table_name')
second_data = second_db_cursor.fetchall()
return default_data, second_data
In the above we accessed the database connections using the connections object.
Happy coding 🥰
Top comments (1)
Hi Kartik, nice explanation, just a favor, would it be possible if you can share your folder structure - for the django project that you have created for the multiple dbs