Django多个数据库(健全性检查)

时间:2017-07-01 12:39:38

标签: python django database router

下午。我已经阅读了很多关于这个主题的地方,从每个地方获取信息,因为它们看起来并不一致,并且相信我有这个工作。由于这是一个测试设置,我不想花几个月的时间来找到一些不起作用的东西 - 而且事实证明是这样的。

感谢那些比我自己更有经验的人,请提出任何建议。

settings.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'myproject',
    'USER': 'myprojectuser',
    'PASSWORD': 'abc123',
    'HOST': 'localhost',
    'PORT': '',
},
'ta1_db': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'testapp1db',
    'USER': 'ta1',
    'PASSWORD': 'ta1',
    'HOST': 'localhost',
    'PORT': '',
},
'ta2_db': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'testapp2db',
    'USER': 'ta2',
    'PASSWORD': 'ta2',
    'HOST': 'localhost',
    'PORT': '',
},
}

DATABASE_ROUTERS = ['spiderproject.routers.DBRouter',]

routers.py(在主spiderproject文件夹中)

class DBRouter(object):

def db_for_read(self, model, **hints):
    """Send all read operations on 'app_label' app models to associated db"""
    if model._meta.app_label == 'testapp1':
        return 'ta1_db'
    if model._meta.app_label == 'testapp2':
        return 'ta2_db'
    return None

def db_for_write(self, model, **hints):
    """Send all write operations on 'app_label' app models to associated db"""
    if model._meta.app_label == 'testapp1':
        return 'ta1_db'
    if model._meta.app_label == 'testapp2':
        return 'ta2_db'
    return None

def allow_relation(self, obj1, obj2, **hints):
    """Determine if relationship is allowed between two objects."""

    # Allow any relation between two models that are in the same app.
    if obj1._meta.app_label == 'testapp1' and obj2._meta.app_label == 'testapp1':
        return True
    if obj1._meta.app_label == 'testapp2' and obj2._meta.app_label == 'testapp2':
        return True
    # No opinion if neither object is in the Example app (defer to default or other routers).
    elif 'testapp1' not in [obj1._meta.app_label, obj2._meta.app_label] and 'testapp2' not in [obj1._meta.app_label, obj2._meta.app_label]:
        return None

    # Block relationship if one object is in the Example app and the other isn't.
        return False

def allow_migrate(self, db, app_label, model_name=None, **hints):
    """Ensure that the 'app_label' app's models get created on the right database."""
    if app_label == 'testapp1':
        return db == 'ta1_db'
    if app_label == 'testapp2':
        return db == 'ta2_db'
    elif db == 'default':
        # Ensure that all other apps don't get migrated on the example_db database.???
        return False

    # No opinion for all other scenarios
    return None

(在allow_migrate()中的elif我不确定是否正确。还有allow_relation()中的elif。我从一个例子改编了这些

我已经在自己的admin.py中注册了testapp1和testapp2的模型,它们出现在管理页面上 - 此时添加/删除数据是正常的,我检查它们是否独立存储。

非常感谢提前。

1 个答案:

答案 0 :(得分:1)

这是我推荐的路由器。以下评论中的解释


class DBRouter(object):
    def db_for_read(self, model, **hints):
        """Send all read operations on 'app_label' app models to associated db"""
        if model._meta.app_label == 'testapp1':
            return 'ta1_db'
        if model._meta.app_label == 'testapp2':
            return 'ta2_db'
        # return None
        
        # I recommend returning 'default' here since 
        # it is your default database
        return 'default'

    def db_for_write(self, model, **hints):
        """Send all write operations on 'app_label' app models to associated db"""
        if model._meta.app_label == 'testapp1':
            return 'ta1_db'
        if model._meta.app_label == 'testapp2':
            return 'ta2_db'
        # return None
        
        # I recommend returning 'default' here since 
        # it is your default database, this will allow
        # commonly used django apps to create their
        # models in the default database (like contenttypes 
        # and django auth
        return 'default'

    def allow_relation(self, obj1, obj2, **hints):
        """Determine if relationship is allowed between two objects."""

        # Allow any relation between two models that are in the same app.
        # I prefer to make this global by using the following syntax
        return obj1._meta.app_label == obj2._meta.app_label


    def allow_migrate(self, db, app_label, model_name=None, **hints):
        
        # I think this was your biggest misunderstanding
        # the db_for_write will pick the correct DB for the migration
        # allow_migrate will only let you say which apps/dbs you 
        # should not migrate.  I *strongly* recommend not taking
        # the belt and braces approach that you had here.        
        return True