Django中不同应用程序的不同数据库

时间:2012-12-07 03:10:39

标签: python django

我的Django网站上有多个应用: mainsite 博客教程

我可以在不同的Django应用程序中使用不同的数据库(例如PostgreSQL,MySQL)吗?

1 个答案:

答案 0 :(得分:26)

以下是您必须要做的事情。

1)更新您要使用的数据库的设置。

settings.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': '/var/db/projectdb'
}
'db_app1': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': '/var/db/app1db'
}
'db_app2': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': '/var/db/app2db'
}

2)对于每个数据库,实现一个数据库路由器,它将适当地路由查询。在你的案例中实现每个应用程序。请注意,这或多或少取自django docs。

app1.dbRouter.py

# DB router for app1

class App1DBRouter(object):
    """
    A router to control app1 db operations
    """
    def db_for_read(self, model, **hints):
        "Point all operations on app1 models to 'db_app1'"
        from django.conf import settings
        if not settings.DATABASES.has_key('db_app1'):
            return None
        if model._meta.app_label == 'app1':
            return 'db_app1'
        return None

    def db_for_write(self, model, **hints):
        "Point all operations on app1 models to 'db_app1'"
        from django.conf import settings
        if not settings.DATABASES.has_key('db_app1'):
            return None
        if model._meta.app_label == 'app1':
            return 'db_app1'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        "Allow any relation if a model in app1 is involved"
        from django.conf import settings
        if not settings.DATABASES.has_key('db_app1'):
            return None
        if obj1._meta.app_label == 'app1' or obj2._meta.app_label == 'app1':
            return True
        return None

    def allow_syncdb(self, db, model):
        "Make sure the app1 app only appears on the 'app1' db"
        from django.conf import settings
        if not settings.DATABASES.has_key('db_app1'):
            return None
        if db == 'db_app1':
            return model._meta.app_label == 'app1'
        elif model._meta.app_label == 'app1':
            return False
        return None

3)在settings.py

中更新DATABASE_ROUTERS

settings.py

DATABASE_ROUTERS = ['app1.dbRouter.App1DBRouter', 'app2.dbRouter.App2DBRouter']

请注意使用Python 3的人

等语句

        if not settings.DATABASES.has_key('db_app1'):

应该成为

        if 'db_app1' not in settings.DATABASES: