Different databases for different apps in Django

Question:

I have multiple apps in my Django site: mainsite, blog and tutorials.

Can I use different databases (e.g. PostgreSQL, MySQL) in different Django apps?

Asked By: Mirage

||

Answers:

Here is what you will have to do to get going.

  1. Update settings for databases that you want to use.

settings.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': '/var/db/projectdb'
}
'db_app1': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': '/var/db/app1db'
}
'db_app2': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': '/var/db/app2db'
}
  1. For each database, implement a database router that will route the queries appropriately. In your case implement in each app. Note this more or less taken from django docs.

dbRouter.py (place in ‘app1’ folder):

# DB router for app1
class App1DBRouter(object):
        """
    A router to control db operations
    """
    route_app_labels = {'app1'}
    db_name = 'db_app1'

    def db_for_read(self, model, **hints):
        """
        Attempts to read auth and contenttypes models go to self.db_name.
        """
        if model._meta.app_label in self.route_app_labels:
            return self.db_name
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write auth and contenttypes models go to self.db_name.
        """
        if model._meta.app_label in self.route_app_labels:
            return self.db_name
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the auth or contenttypes apps is
        involved.
        """
        if (
            obj1._meta.app_label in self.route_app_labels or
            obj2._meta.app_label in self.route_app_labels
        ):
           return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Make sure the auth and contenttypes apps only appear in the
        self.db_name database.
        """
        if app_label in self.route_app_labels:
            return db == self.db_name
        return None
  1. Update DATABASE_ROUTERS in settings.py

settings.py

DATABASE_ROUTERS = ['app1.dbRouter.App1DBRouter', 'app2.dbRouter.App2DBRouter']
Answered By: Rohan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.