How to Use Multiple Databases in Django
Aug. 15, 2022Django ORM very well designed to use multiple relational databases (regardless engine) in single project. To start using two databases in Django project you need to configure connection to all of them in the settings.py
file.
Configuration
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'global_airports_sqlite.db',
}
'second_database': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'second_database.db',
}
}
Once it will be configured you can query data from the database that is not ‘default’ using using('<database_connection_name>')
Post.objects.using('second_database').all()
Same for write
Post.objects.using('second_database').create(
name='First Post',
category_id=1,
)
It also can be more dynamic, you can assign database connection name to the variable and use it this way
database_name = 'second_database'
Post.objects.using(database_name).create(
name='First Post',
category_id=1,
)
Migrations
By default Django assume that any model can by queried using any configured database, so you need to apply migrations for each database.
Widely used command python manage.py migrate
apply migrations to all database, to apply migrations to the specific database you may to to specify database connection name this way
python manage.py migrate --database=second_database
If you need more flexible configuration using multiple databases such as
- Limit some model to use some database by default
- Limit all models from the some app to use some database by default
- Apply only certain migrations migrations per app/model
- Allow relation (foreignKey/one-to-one) between objects in different databases
It is all possible but you need to create your custom database router.