views:

533

answers:

2

Are there common patterns people use for creating multi-tenanted applications using Django. The built in "sites" framework seems like an option. Are there other approaches people have had success with?

+2  A: 

Using the sites framework goes a long way towards providing a security guarantee to the "tenants", assuming you give each site instance a unique table.

On the other hand, it'll be a big hassle if you have a small number of tenants and you'll waste a huge amount of server resources since you'll need at least one server process per customer even if they aren't using the system. If you have a large number of tenants it won't be quite as much hassle because you'll be forced to automate the solution regardless of your approach.

Putting a tenant foreign key in almost all your models will work just fine and Django's ORM makes it easy (easier?) to enforce security using custom managers. The drawback is performance if you start getting hammered with lots of users, because there's no easy way to scale up.

If you do need to scale, I think the best solution could be a combination of both approaches. Every model has a tenant foreignkey so databases can be shared but then you develop some mechanism at a higher level than Django to route customers into a site instance. This lets you put really big tenants on their own databases with resources properly tuned just for them (e.g. the proper number of mod_wsgi daemons, number of database connections, memcache pool properly sized, etc.) and smaller tenants share common resources.

Van Gale
A: 

Hi Van Gale,

I'm a new guy of Django and i'm facing the same problem with hlovdal, as you mentioned, we can use a tenant_id in each table, so i'm wondering how to combine django admin/user with tenant, could you give more detail here?

Thanks

Jason

Jason
I'm not the OP but here's what I ended up doing. First off I didn't use sites. The problem with sites it's it's tied to web server hosts which I don't want. For my app the issue is tying the user to a tenant. I've got a helper function in views.py that given the request user gives you the tenant id for that user. The user profile for a user has the users tenant. I've got custom managers that have a method which takes the tenant id and automatically filters down to just the rows for that tenant. This feels like it should be common enough to be native in the ORM but it's not.