Multiple Databases in Django

dj221ai

D

Posted on August 5, 2020

Multiple Databases in Django

This post was Originally from my medium posts.

In this tutorial we gonna see how we can use multiple databases in django. In this tutorial we used django 3.0 but it will be suitable for all version of django ≥ above 2.2.
let first create a directory and setup the virtual environment for this project. I am using python 3.6 and Django 3.0 for this project.
Go to the folder in which you want to create the project and install django and the other required things.(It would be much better if you create the project in virtual environment it will separate this project from your other projects).
Create Project called checkingdb
djanog-admin startproject checkingdb
cd checkingdb
python manage.py startapp contenter, python manage.py startapp customer, python manage.py startapp userchecking
Now in settings.py file the db’s gets configured, but first start your pgAdmin if you are using postgres and create new databases. here i have created 3 db’s named contentdb, usersdb, customerdb where contentdb is the default one and the other two are the extra db’s which you can use for other purposes.
First add all your apps in INSTALLED_APPS and now lets configure the DATABASE_ROUTERS.
DATABASE_ROUTERS = ['contenter.router.CheckerRouter'] # it consists the path where your router.py file reside. in my case it is in contenter app.
Now lets configure the database in settings
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'contentdb',
'USER': 'postgres',
'PASSWORD': 'admin1234',
'HOST': 'localhost',
'PORT': '5432'
},
'usersdb': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'usersdb',
'USER': 'postgres',
'PASSWORD': 'admin1234',
'HOST': 'localhost',
'PORT': '5432'
},
'customerdb': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'customerdb',
'USER': 'postgres',
'PASSWORD': 'admin1234',
'HOST': 'localhost',
'PORT': '5432'
}

}
I have created the router.py file in contenter app. below is the code for router.py file.
class CheckerRouter:

def db_for_read(self, model, **hints):
    if model._meta.app_label == 'customers':
        return 'customerdb'
    elif model._meta.app_label == 'userchecking':
        return 'usersdb'
    return 'default'

def db_for_write(self, model, **hints):
    if model._meta.app_label == 'customers':
        return 'customerdb'
    elif model._meta.app_label == 'userchecking':
        return 'usersdb'
    return 'default'

def allow_relation(self, obj1, obj2, **hints):
    if obj1._meta.app_label == 'customers' or obj2._meta.app_label == 'customers':
        return True
    elif 'customers' not in [obj1._meta.app_label, obj2._meta.app_label]:
        return True
    elif obj1._meta.app_label == 'userchecking' or obj2._meta.app_label == 'userchecking':
        return True
    elif 'userchecking' not in [obj1._meta.app_label, obj2._meta.app_label]:
        return True
    return False

def allow_migrate(self, db, app_label, model_name=None, **hints):
    if app_label == 'customers':
        return db == 'customerdb'
    elif app_label == 'userchecking':
        return db == 'usersdb'
    return None
Enter fullscreen mode Exit fullscreen mode

Now need to do some changes in models.py in all apps and we are good to go.
contenter\models.py
from django.db import models

class Content(models.Model):
app_name = models.CharField(max_length=100)
language = models.CharField(max_length=100)

def __str__(self):
    return self.app_name
Enter fullscreen mode Exit fullscreen mode

customers\models.py
from django.db import models

class CustomerChecker(models.Model):
customer_name = models.CharField(max_length=100)

class Meta:
    # app_label helps django to recognize your db
    app_label = 'customers'

def __str__(self):
    return self.customer_name
Enter fullscreen mode Exit fullscreen mode

userchecking\models.py
from django.db import models

class UserChecker(models.Model):
user_name = models.CharField(max_length=100)
age = models.IntegerField()

class Meta:
    app_label = 'userchecking'  # name of app

def __str__(self):
    return self.user_name
Enter fullscreen mode Exit fullscreen mode

Don’t forget to include your models in admin.py file.
After all these need to migrate all the apps
python manage.py migrate — database=customerdb
python manage.py migrate — database=usersdb
python manage.py migrate
than run the server using python manage.py runserver and go to browser
and type localhost:8000/admin and login and add data in your models and check in your db.
Note:- When you change anything in models don’t forget to use Python manage.py makemigrations.

💖 💪 🙅 🚩
dj221ai
D

Posted on August 5, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related