Is there a way to specify that a model (or app, even) should only ever use one particular database?
I am working with a legacy database that I don\'t want to change.
Tested with Django 2.2 and pytest.
Just to streamline a bit the excellent @chris-schon answer:
class LegacyDbModel(models.Model):
class Meta:
abstract = True
_db = 'legacy_db_alias'
class LegacyDbRouter(object):
def db_for_read(self, model, **hints):
""" reading model based on params """
if not hasattr(model, 'Meta'):
return None
return getattr(model.Meta, '_db', None)
def db_for_write(self, model, **hints):
""" writing model based on params """
if not hasattr(model, 'Meta'):
return None
return getattr(model.Meta, '_db', None)
It has couple of minor benefits:
params nested class for models from default DB.Meta nested class which is already part of Django.allow_migrate even for tests.The only drawback is that we need to inherit from Meta explicitly:
class LegacyModel(LegacyDbModel):
# ... docs, fields, etc.
class Meta(LegacyDbModel.Meta):
managed = False
db_table = 'legacy_table'
But even that is more aligned with how Django works.
Remember:
Explicit is better than implicit.