Django - how to specify a database for a model?

前端 未结 6 1402
滥情空心
滥情空心 2020-11-29 04:53

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.

6条回答
  •  佛祖请我去吃肉
    2020-11-29 05:51

    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:

    1. We don't need a params nested class for models from default DB.
    2. We leverage Meta nested class which is already part of Django.
    3. Router works without 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.

提交回复
热议问题