Django - how to specify a database for a model?

前端 未结 6 1406
滥情空心
滥情空心 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:53

    I found that you can route models pretty simply with this manager:

    class SecondDbManager(models.Manager):
        def get_queryset(self):
            qs = super().get_queryset()
    
            # if `use_db` is set on model use that for choosing the DB
            if hasattr(self.model, 'use_db'):
                qs = qs.using(self.model.use_db)
    
            return qs
    

    Just add use_db='databasename' and this manager to your model and it works.

    Or to further simplify it I created a base model for it:

    class SecondDbBase(models.Model):
        use_db = 'my_second_db'
        objects = SecondDbManager()
    
        class Meta:
            abstract = True
    

    And with this all you need to do is extend it like so. Instead of:

    class Customer(models.Model):
    

    Just do this and it works:

    class Customer(SecondDbBase):
    

    PS. I'm not sure if it's a good practice or the best solution but it works and routing to other databases is a breeze :)

    PPS. I've only ever used these for only reading and writing tables that are not managed by Django(managed = False) so if you need to create migrations for them, I'm not sure if it works or not. Might still need to use DATABASE_ROUTERS for that.

提交回复
热议问题