Skip to content Skip to sidebar Skip to footer

How To Use Db Router In Django 1.4

I've been trying to setup Django 1.4.3 to use multiple DBs, but for the life of me I can't make it to work. I read the documentation and posts on SO, and did the following: 1) Add

Solution 1:

I found out that the statement in step 3 "from django.db import connections " was preventing the DB router to be registered. When I removed this statement, the router was registered and stuff started to work as expected.

Solution 2:

I think the problem is probably arising because your routers.py only returns a reference to 'db1' but as you say you're only being routed to 'default' I'm unsure (I would expect it to be the only routed to 'db1'.

In routers.py create a master router class, and then subclass for each DB - and initialise with an app_label string so you can set them apart.

classMasterRouter(object):
    def__init__(self, app_label):
        super(MasterRouter, self).__init__()
        self.app_label = app_label

    defdb_for_read(self, model, **hints):
        if model._meta.app_label == self.app_label:
            return self.app_label
        returnNonedefdb_for_write(self, model, **hints):
        if model._meta.app_label == self.app_label:
            return self.app_label
        returnNonedefallow_relation(self, obj1, obj2, **hints):
        if obj1._meta.app_label == self.app_label or obj2._meta.app_label == self.app_label:
            returnTruereturnNonedefallow_syncdb(self, db, model):
        if db == 'default':
            return model._meta.app_label == self.app_label
        elif model._meta.app_label == self.app_label:
            returnFalsereturnNoneclassDefaultRouter(MasterRouter):
    def__init__(self):
        super(DefaultRouter, self).__init__('default')

classDB1Router(MasterRouter):
    def__init__(self):
        super(DB1Router, self).__init__('db1')

and then in your settings.py declare the routers

DATABASE_ROUTERS = [ 'routers.DefaultRouter', 'routers.DB1Router' ]

ofcourse, you'll probably want to set up your MasterRouter class overrides differently.

Post a Comment for "How To Use Db Router In Django 1.4"