Different database for each django site

Suppose we have multiple sites (using sites-framework of Django) running on the same django instance.

MyModel.objects.filter(site_id=request.site, slug=slug)[0] might be an overhead in the future. So I was wondering if I could split the databases for this model(s) for querying faster.

So if request.site is 1, running

MyModel.objects.get(slug=slug)

will query only db1.

If request.site is 2, running

MyModel.objects.get(slug=slug)

will query only db2.

I will be getting request.site from the request parameter of the view as value of site will be dynamically determined according to the subdomain used: de, fr, etc.

Answers


You may create a custom router to do this:

Example:

def get_current_site():
   SITE_ID = getattr(settings, 'SITE_ID', 1)
   site_name = Site.objects.get(id=SITE_ID)
   return site_name


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

You can readup more here https://docs.djangoproject.com/en/dev/topics/db/multi-db/


Need Your Help

Retrieve custom SQL entries in Django login

python sql django django-models django-views

Here is my models.py file of my auth app: [which creates a auth_article table in sql]

Fun with JSTL looping and int conversion into a char

jsp jstl el

What I need is a jsp using jstl that will output column labels as Chars (A, B, C...) instead of ints (1, 2, 3...) and just for fun, when the int is greater than 26 it should output AA, AB, AC...oh ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.