【问题标题】:how can I use separate database for every application in django如何为 django 中的每个应用程序使用单独的数据库
【发布时间】:2011-09-26 11:58:43
【问题描述】:

我有 app1 和 app2,我想 app1 使用 db1,app2 使用 db2

我找到的方法是使用数据库路由器,有点复杂

我想知道有什么简单的方法吗?

我可以在 settings.py 中配置它吗

【问题讨论】:

  • @IgnacioVazquez-Abrams 有人会想要这个,因为在某些情况下,您有一个单独的哈希键应用程序,您希望在单独的数据库中保持它们的私密性

标签: python database django


【解决方案1】:

没有。正确的方法是使用路由器。这很简单。请参阅 django 文档中的MyAppRouterhttps://docs.djangoproject.com/en/dev/topics/db/multi-db/#an-example

class MyAppRouter(object):
    """A router to control all database operations on models in
    the myapp application"""

    def db_for_read(self, model, **hints):
        "Point all operations on myapp models to 'other'"
        if model._meta.app_label == 'myapp':
            return 'other'
        return None

    def db_for_write(self, model, **hints):
        "Point all operations on myapp models to 'other'"
        if model._meta.app_label == 'myapp':
            return 'other'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        "Allow any relation if a model in myapp is involved"
        if obj1._meta.app_label == 'myapp' or obj2._meta.app_label == 'myapp':
            return True
        return None

    def allow_syncdb(self, db, model):
        "Make sure the myapp app only appears on the 'other' db"
        if db == 'other':
            return model._meta.app_label == 'myapp'
        elif model._meta.app_label == 'myapp':
            return False
        return None

【讨论】:

  • 谢谢,我会去路由器:D
【解决方案2】:

我认为正确的答案在这里:http://diegobz.net/2011/02/10/django-database-router-using-settings。如果您有许多应用程序并且想要为每个应用程序单独的数据库,您可以放置​​

DATABASE_APPS_MAPPING = {'app1':'db1', 'app2':'db2', 'app3':'db3', 'app4':'db4'}
DATABASE_ROUTERS += ['DatabaseAppsRouter']

进入settings.py。

【讨论】:

    猜你喜欢
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    相关资源
    最近更新 更多