1

I'd like to route (change) the database based on the authenticated user. I've looked at the docs but I don't know how to do this upon user login...

I was thinking of adding a field with database_name to my custom UserProfile and then I'd like to pass this info to the database router which would make the switch...

I don't have any code to show because I simply don't know how to implement this.

This post somehow relates to my previous post.

So the schema would be like:

- Users (containing only the `UserProfile`)
 - user1 (containing the app database)
 - user2 (containing the app database)
 - ...

Could you point me to the right direction?

Thank you! BR

Community
  • 1
  • 1
Mission
  • 1,287
  • 3
  • 16
  • 31
  • 1
    You will probably want to write [a middleware function](https://docs.djangoproject.com/en/dev/topics/http/middleware/) that checks every incoming request, gets the current user and checks a flag in their user profile, routing accordingly. – Timmy O'Mahony Mar 11 '12 at 08:38
  • What's the relationship between databases and users? Is it a horizontal splitting of user table, or use different DB for model mapping for different users? – okm Mar 11 '12 at 08:38
  • Refer to [this][1] post on how to play around with the routers [1]: http://stackoverflow.com/questions/12352360/different-database-for-each-django-site/12353583#12353583 – karthikr Sep 22 '12 at 23:13

2 Answers2

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
Community
  • 1
  • 1
karthikr
  • 97,368
  • 26
  • 197
  • 188
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.

ashwoods
  • 2,209
  • 1
  • 22
  • 36
  • This approach is nice... but I don't really need subdomains and I'm kinda new to Django so hacking is a bit of a problem. – Mission Mar 19 '12 at 13:08