Steven Rogers
Steven Rogers

Reputation: 1994

Route single model to alternate database in django

I have two databases set up in my settings folder of my project

'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'foo': {
    'NAME': 'bar',
    'ENGINE': 'django.db.backends.mysql',
    'HOST': 'some.site.com',
    'USER': 'xxxxxx',
    'PASSWORD': 'xxxxxxxx'
}

I also have models set up, one of them was created with

python manage.py inspectdb --database foo > tmp.py

That created some models I already had in foo, so I copied it over into my models folder. However, django is trying to use the existing default database for that model, when instead I want it to route to the foo database instead.

When looking online for how to get this done. Posts recommend using 'database-routing', but I cannot find documentation or an example that works for me or that I understand.

So please, what is the right way to set up a single model to use an external database?

Upvotes: 1

Views: 265

Answers (1)

Dariusz Bączkowski
Dariusz Bączkowski

Reputation: 410

The easiest way is to select database manually. From https://docs.djangoproject.com/en/1.8/topics/db/multi-db/#manually-selecting-a-database

>>> # This will run on the 'default' database.
>>> Author.objects.all()

>>> # So will this.
>>> Author.objects.using('default').all()

>>> # This will run on the 'other' database.
>>> Author.objects.using('other').all()

>>> my_object.save(using='legacy_users')

Documentation has also other options, check: https://docs.djangoproject.com/en/1.8/topics/db/multi-db/

Upvotes: 1

Related Questions