Skip to content Skip to sidebar Skip to footer

Multiple Database Support In Django

From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet. Can anyone please tell me how one can

Solution 1:

If you simply need multiple connections, you can do something like this:

from django.db import load_backend
myBackend = load_backend('postgresql_psycopg2') # or 'mysql', 'sqlite3', 'oracle'
myConnection = myBackend.DatabaseWrapper({
    'DATABASE_HOST': '192.168.1.1',
    'DATABASE_NAME': 'my_database',
    'DATABASE_OPTIONS': {},
    'DATABASE_PASSWORD': "",
    'DATABASE_PORT': "",
    'DATABASE_USER': "my_user",
    'TIME_ZONE': "America/New_York",})
# Now we can do all the standard raw sql stuff with myConnection.
myCursor = myConnection.cursor()
myCursor.execute("SELECT COUNT(1) FROM my_table;")
myCursor.fetchone()

Solution 2:


Solution 3:

The most recent discussion I've seen on it was in the Proposal: user-friendly API for multi-database support django-developers thread, which also has an example of one way to use multiple databases using Managers in the original message.


Solution 4:

If you read a few of the many (many) threads on this subject in django-dev, you will see that what looks straightforward, isn't. If you pick a single use case, then it looks easy, but as soon as you start to generalize in any way you start to run into trouble.

To use the above-referenced thread as an example, when you say "multiple databases", which of the following are you talking about?

  • All DB on the same machine under the same engine.
  • All DB on same machine, different engines (E.g. MySQL + PostgreSQL)
  • One Master DB with N read-only slaves on different machines.
  • Sharding of tables across multiple DB servers.

Will you need:

  • Foreign keys across DBs
  • JOINs across machines and/or engines
  • etc. etc.

One of the problems with a slick ORM like Django's is that it hides all of those messy details under a nice paint job. To continue to do that, but to then add in any of the above, is Not Easy (tm).


Solution 5:

Eric Florenzano wrote a very good blog post that allows you some multiple database support at: Easy MultipleDatabase Support for Django.

It starts by creating a new custom manager that allows you to specify the database settings.


Post a Comment for "Multiple Database Support In Django"