Django - how to specify a database for a model?
Solution 1:
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': {
....
}
}
Solution 2:
As far as I know you can't specify the database directly with the model since it would kind of prevent the app from ever being reusable, but from what I can see in the docs:
https://docs.djangoproject.com/en/1.8/topics/db/multi-db/