0

I have 2 database routers, both with very basic logic such as:

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

With settings:

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

Debugging, with break points, or just by inserting exceptions, I can see that db_for_read() and db_for_write() are called just fine, but allow_relation() is seemingly never called, and instead I am encountering errors such as:

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

As a result of trying to access a relation which I would expect to trigger allow_relation():

my_model_2.my_model_1
DanH
  • 5,498
  • 4
  • 49
  • 72
  • 1
    `allow_relation()` should be triggered when you try to create a relation, as it is ["for validation purposes"](https://docs.djangoproject.com/en/1.9/topics/db/multi-db/#allow_relation), not when you ry to read it. (In this case you'll just get an error). So try to create a relation for those models to test if this method is triggered. – Nikita Mar 11 '16 at 11:29
  • Ahh right, so this has no bearing on `my_model_2.my_model_1`. Thanks! – DanH Mar 11 '16 at 11:36

0 Answers0