[Django]-Django multiple database mapping

3👍

Let’s say I can import a function that gives me the database:

project/app/views.py:

from .utils import which_db, item_search
from django.shortcuts import render
from .models import SomeModel

def some_view(request):
    obj = SomeModel.objects.using(which_db(request)).filter(**item_search(request))
    return render(request, "some_model.html", {'object':obj}

It’s a bother having to append the using every time. There is a way to route similar queries to different databases (documented here in more detail).

project/settings.py:

DATABASE_ROUTERS = ['project.db_routes.AppRouter',]
DB_ROUTING = {'app1':'db1','app2':'db2'}

project/db_routes.py:

from django.conf import settings


class AppRouter:
    def __init__(self):
        self.DB = settings.DB_ROUTING

    def db_for_read(self, model, **hints):
        return self.DB.get(self.model.app_label, 'default')

    def db_for_write(self, model, **hints):
        return self.DB.get(self.model.app_label, 'default')

    def allow_relation(self, obj1, obj2, **hints):
        return True

    def allow_migrate(self, db, app_label, model=None, **hints):
        return self.DB.get(app_label, None)

I’m assuming you want to be able to have foreignkeys between the databases. If not, return False from allow_relation. allow_migrate insures objects only exists in their proper database.

I have not tested this solution, but it does conform to the documentation.

0👍

I’m not entirely sure what you want to do. But my guess is that you’ll find your answer here:

https://docs.djangoproject.com/en/1.8/topics/db/multi-db/#topics-db-multi-db-routing

If you really want to select a database based on the url (subdomain e.a.) than you will have to write a custom Middleware class:

https://docs.djangoproject.com/en/1.8/topics/http/middleware/

Leave a comment