Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Django
  • Views
  • Model
  • Template
  • Forms
  • Jinja
  • Python SQLite
  • Flask
  • Json
  • Postman
  • Interview Ques
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJS
  • Vue.js
Open In App
Next Article:
Delete Multiple Objects at Once in Django
Next article icon

Working with Multiple Databases in Django

Last Updated : 31 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

hhh

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


Next Article
Delete Multiple Objects at Once in Django

R

rs736tjxi
Improve
Article Tags :
  • Python
  • Django
  • Python Django
Practice Tags :
  • python

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences