Django多个dbs上的多个应用程序

时间:2014-01-28 20:22:50

标签: django django-orm

所以我正在开发一个项目,每个应用程序都有自己的数据库。但是,当我同步数据库时,只会同步默认数据库。我需要帮助才能看到问题。

# from settings.py
try:
    from local_settings import *
    INSTALLED_APPS += LOCAL_APPS
    for app in LOCAL_APPS:
        _appdb = DATABASES['default'].copy()
        _appdb['NAME'] = app
        DATABASES[app] = _appdb
except ImportError:
    pass

我已经确认每个本地应用都有动态生成的相应数据库。这是db router

import os

MY_LOCAL_APPS = []
with open(os.path.join(os.path.dirname(__file__), "apps.csv")) as appsfile:
    MY_LOCAL_APPS = appsfile.readlines()

MY_LOCAL_APPS = [x.strip() for x in MY_LOCAL_APPS]

class JauntRouter(object):
    def db_for_read(self, model, **hints):
        """
        Attempts to read app models go to app_db.
        """
        if model._meta.app_label in MY_LOCAL_APPS: 
            return model._meta.app_label
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write app models go to app_db.
        """
        if model._meta.app_label in MY_LOCAL_APPS: 
            return model._meta.app_label
        return None

    def allow_relation(self, obj1, obj2, **hints):
        if model._meta.app_label in MY_LOCAL_APPS: 
            return model._meta.app_label
        return None

    def allow_syncdb(self, db, model):
        if db in MY_LOCAL_APPS:
            return model._meta.app_label == db
        return None

但是,当我运行syncdb时,会在default数据库中创建表。请注意,我已从设置文件中打印出INSTALLED_APPSDATABASES,但它们显示正确,因此我认为不是问题所在。

非常感谢帮助。

1 个答案:

答案 0 :(得分:1)