定义的数据库路由器永远不会调用`allow_relation()`

时间:2016-03-11 11:21:37

标签: python django django-database

我有2个数据库路由器,都有非常基本的逻辑,如:

class App2Router(object):

    def db_for_read(self, model, **hints):
        if model._meta.app_label == 'app2' and model._meta.object_name == 'MyModel2':
            return 'db2'
        return None

    def db_for_write(self, model, **hints):
        if model._meta.app_label == 'app2' and model._meta.object_name == 'MyModel2':
            return 'db2'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        # Disallow relations involving MyModel2 since it's on its own database isolated.
        if 'app2' in [obj1._meta.app_label, obj2._meta.app_label] and \
                'MyModel2' in [obj1._meta.object_name, obj2._meta.object_name]:
            return False
        return None

    def allow_syncdb(self, db, model):
        return False

使用设置:

DATABASE_ROUTERS = [
    'app1.routers.App1Router',
    'app2.routers.App2Router',
]

使用断点进行调试,或者只是插入例外,我可以看到db_for_read()db_for_write()被称为正常,但allow_relation()似乎从未被调用,而是我遇到错误,例如:

(1146, "Table 'DB2.app1_mymodel1' doesn't exist")

尝试访问我希望触发allow_relation()的关系:

my_model_2.my_model_1

0 个答案:

没有答案