Django - how to specify a database for a model?

pfctdayelise picture pfctdayelise · Aug 19, 2010 · Viewed 26.9k times · Source

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. I have two databases - the 'default' is an sqlite one that could be used for admin etc, and the legacy one. I used inspectdb to create a model for (part of) the legacy database, and it has managed = False. But is there a way to specify in the model itself that it only applies to a particular database?

I see that you can specify using=databasename in some query sets etc but this is no good for things like Databrowse (and possibly also generic views?). It might be a short-coming of Databrowse that you can't specify a database, but it just seems like the right place to specify it is the model...

Then I thought maybe the answer is to write a custom model manager that only refers to my legacy database - but the docs don't mention anything like that.

Do I just have a different mental model of how multiple databases might be used, to the Django world?

Answer

Juan José Brown picture Juan José Brown · Dec 19, 2017

You can't specify a database for a model, but you can define it in a custom DB router class.

# app/models.py
class SomeModel(models.Model):
    ...

# app/dbrouters.py
from app.models import SomeModel
...
class MyDBRouter(object):

    def db_for_read(self, model, **hints):
        """ reading SomeModel from otherdb """
        if model == SomeModel:
            return 'otherdb'
        return None

    def db_for_write(self, model, **hints):
        """ writing SomeModel to otherdb """
        if model == SomeModel:
            return 'otherdb'
        return None


# app/settings.py
DATABASE_ROUTERS = ('app.dbrouters.MyDBRouter',)
...
DATABASES = {
    ...
    'otherdb': {
        ....
    }
}