Working with Multiple Databases in Django
Last Updated :
31 Jul, 2024
Django stands out as a powerful and versatile framework for building dynamic and scalable applications. One of its notable features is its robust support for database management, offering developers flexibility in choosing and integrating various database systems into their projects. In this article, we will see how to use Multiple Databases with Django.
Using Multiple Databases with Django
Here, we will see step-by-step how to connect Using Multiple Databases with Django in Python:
Starting the Project Folder
To start the project use this command
django-admin startproject core
cd core
To start the app use this command
python manage.py startapp home
Now add this app to the ‘settings.py’
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"home",
"rest_framework"
]
Install required packages
pip install djangorestframework
File Structure

Setting Necessary Files
models.py : Below, code defines a Django model called Paragraph with fields for a user reference, name, and description, using Django's user model and settings for flexibility.
Python
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
from django.utils import timezone
from django.conf import settings
class Paragraph(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL, null=True, blank=True)
paragraph_name = models.CharField(max_length=100)
paragraph_description = models.TextField()
views.py : This Python code uses Django REST Framework to create a viewset for the Paragraph model, enabling CRUD operations (Create, Retrieve, Update, Delete) through API endpoints. It includes filtering capabilities based on the paragraph name and description fields.
Python
from rest_framework import viewsets, filters, permissions
from .models import Paragraph
from .serializers import ParagraphSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class ParagraphViewSet(viewsets.ModelViewSet):
queryset = Paragraph.objects.all()
serializer_class = ParagraphSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['paragraph_name', 'paragraph_description']
serializers.py: This Python code creates a serializer for the Paragraph model, using Django REST Framework, to handle conversion to and from JSON format for all fields of the model.
Python
from rest_framework import serializers
from .models import Paragraph
class ParagraphSerializer(serializers.ModelSerializer):
class Meta:
model = Paragraph
fields = '__all__'
home/urls.py: This Django code sets up URL patterns for the ParagraphViewSet, utilizing Django REST Framework's DefaultRouter to enable CRUD operations on the 'Paragraph' model via '/recipes/'.
Python
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import ParagraphViewSet
router = DefaultRouter()
router.register(r'recipes', ParagraphViewSet)
urlpatterns = [
path('', include(router.urls)),
]
core/urls.py: This Django code defines URL patterns, routing requests to the admin interface at '/admin/' and including URLs from the 'home' app at the root path.
Python
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('home.urls')),
]
admin.py Here we are registering our models.
Python
from django.contrib import admin
from .models import *
from django.db.models import Sum
admin.site.register(Paragraph)
Configure Django settings for PostgreSQL update below code in settings.py file
Python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
},
'postgresql': {
# replace below information with your information
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres1',
'USER': 'postgres',
'PASSWORD': '1234',
'HOST': 'localhost',
'PORT': '5432',
}
}
Configure Django settings for MySQL update below code in settings.py file
Python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
},
'mysql': {
# replace below information with your information
'ENGINE': 'django.db.backends.mysql',
'NAME': 'my_db',
'USER': 'root',
'PASSWORD': 'admin',
'HOST': 'localhost',
'PORT': '3306',
}
}
Deployment of the Project
Run these commands to apply the migrations:
python3 manage.py makemigrations
python3 manage.py migrate
For create the superuser use the below command :
python3 manage.py createsuperuser
Run the server with the help of following command:
python3 manage.py runserver
for flush the databse use the below command
python3.manage.py flush
Output
Similar Reads
Delete Multiple Objects at Once in Django
In Django, deletions of objects are very common once we want to delete outdated information or information we no longer have a need for within our database. Django ORM provides several and efficient ways to delete models instances. To delete instances in Django, we can use either of the following me
3 min read
Multiple Postgres databases in psycopg2
PostgreSQL is the most powerful open-source object-relational database management system. Psycopg2 is the most popular PostgreSQL database adapter for Python language. It simply allows you to work with multiple databases in the same program at the same time. This indicates that you can easily switch
4 min read
How to integrate Mysql database with Django?
Django is a Python-based web framework that allows you to quickly create efficient web applications. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database â SQLlite3, etc. Installation Let's first un
2 min read
Database Functions in Django
In Django, database functions play an important role in querying, manipulating, and managing data stored in your application's database. In this article, we will learn about database functions in Django. What are Database Functions in Django?In Django, functions such as annotate, aggregate, and filt
4 min read
How to Run Django's Test Using In-Memory Database
By default, Django creates a test database in the file system, but it's possible to run tests using an in-memory database, which can make our tests faster because it avoids disk I/O operations. In this article, weâll explore how to run Django tests with an in-memory database, the advantages of this
6 min read
Django Squashing Database Migrations Files
Migrations are Django's way of propagating changes we make to our models (adding a field, deleting a model, etc.) into our database schema. Migrations in Django propagate model changes (like adding a field) to our database schema. The key commands are: migrate: Applies and unapplied migrations.makem
7 min read
Django Transaction System with Database Updates
In today's digital age, transaction systems play a pivotal role in various industries, from e-commerce platforms to banking and beyond. These systems are responsible for handling financial operations, ensuring data accuracy, and providing a seamless user experience. One of the most powerful tools fo
4 min read
How to combine multiple QuerySets in Django?
QuerySets allow you to filter, order, and manipulate data from your database using a high-level Pythonic syntax. However, there are situations where you may need to combine multiple QuerySets into a single QuerySet to work with the data more efficiently. This article will explore various methods to
5 min read
How to use PostgreSQL Database in Django?
This article revolves around how can you change your default Django SQLite-server to PostgreSQL. PostgreSQL and SQLite are the most widely used RDBMS relational database management systems. They are both open-source and free. There are some major differences that you should be consider when you are
2 min read
How to Create a Basic Project using MVT in Django ?
Prerequisite - Django Project MVT Structure Assuming you have gone through the previous article. This article focuses on creating a basic project to render a template using MVT architecture. We will use MVT (Models, Views, Templates) to render data to a local server. Create a basic Project: To initi
2 min read