Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - how to specify a database for a model?

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?

like image 557
pfctdayelise Avatar asked Aug 19 '10 06:08

pfctdayelise


People also ask

Can we use 2 databases in Django?

Django's admin doesn't have any explicit support for multiple databases. If you want to provide an admin interface for a model on a database other than that specified by your router chain, you'll need to write custom ModelAdmin classes that will direct the admin to use a specific database for content.

Is Django model a database?

Each model is a Python class that subclasses django.db.models.Model . Each attribute of the model represents a database field. With all of this, Django gives you an automatically-generated database-access API; see Making queries.


1 Answers

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': {         ....     } } 
like image 114
Juan José Brown Avatar answered Nov 15 '22 23:11

Juan José Brown