Django - how to specify a database for a model?

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

    The simple solution is to set the manager to always use a specific database for the model. Look into Django's using.

    Example:

    class User(models.Model):
        birth_date = models.DateField()
    
        class Meta:
            managed = False
            db_table = 'myotherapp_user'
    
    User.objects = User.objects.using('myotherdb')
    

    Then you can use User.objects and it will always use the 'myotherdb' database instead of 'default'.

    Note that relations between models from different databases will not work, but this is an issue with Django since it does not support this out of the box.

提交回复
热议问题