如何在Django中为每个应用使用独立数据库

3 投票
2 回答
3209 浏览
提问于 2025-04-16 20:38

我有两个应用,app1和app2,我想让app1使用数据库db1,而app2使用数据库db2。

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

我想知道有没有更简单的方法?

我能不能直接在settings.py里配置一下?

2 个回答

3

我觉得正确的答案在这里: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文件里。

4

不,正确的方法是使用路由器。这非常简单。可以查看Django文档中的MyAppRouter部分:https://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

撰写回答