[Answered ]-Django database router

1👍

Multitenancy in general is a little bit hard to do without twisting django a bit, even though it is a typical request in SaaS applications. Here is a link describing one approach, the one developed at a company I worked with was a little bit different, hacking the contrib.sites, but the database part is pretty similar.

In short, if you want database multitenancy you are going to have to hack Django ConnectionHandler to do what you want.

1👍

Refer to this post on how to play around with the routers

DATABASE_ROUTERS = ['CustomDatabaseRouter',] #a setting that Django understands.

class CustomDatabaseRouter(object):

  def db_for_read(self, model, **hints):
     site_name = get_current_site()
     if site_name  in ['site1']:
         return 'db1'
     if site_name in ['site2']:
        return 'db2'
     return 'default'

  def db_for_write(self, model, **hints):
     site_name = get_current_site()
     if site_name  in ['site1']:
         return 'db1'
     if site_name in ['site2']:
        return 'db2'
     return 'default'

  def allow_syncdb(self, model, **hints):
     site_name = get_current_site()
     if site_name in ['site1'] and db == 'db1':
         return True
     if site_name in ['site2'] and db == 'db2':
        return True
     return False

Leave a comment