Different database for each django site

懵懂的女人 提交于 2019-12-02 01:06:32

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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!