Python 定义的数据库路由器从不调用'allow_relation()`
我有2个数据库路由器,它们都具有非常基本的逻辑,例如:Python 定义的数据库路由器从不调用'allow_relation()`,python,django,django-database,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
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\u for_read()
和db\u for_write()
调用得很好,但是allow\u relation()
似乎从未调用过,相反,我遇到了如下错误:
(1146, "Table 'DB2.app1_mymodel1' doesn't exist")
由于尝试访问一个我希望触发的关系allow\u relation()
:
allow\u relation()
应该在尝试创建关系时触发,而不是在尝试读取关系时触发。(在这种情况下,您只会得到一个错误)。因此,尝试为这些模型创建一个关系,以测试是否触发了此方法。啊,对,因此这与my\u model\u 2.my\u model\u 1
无关。谢谢
my_model_2.my_model_1