[Django]-Can I query a secondary database from Django without ORM?

8👍

You have two options:

  1. ORM-less:
    simply install and import the Python driver for your second database (MySQLdb for MySQL, psycopg2 for PostgreSQL, etc.), then create a connection and run plain SQL queries without any usage of Django. The details on this can be found in the docs of respective database drivers.

  2. ORM-ful:

    • Add a second database in your settings.py:

      DATABASES = {
        'default': {
          # your Django db settings here
        },
        'second': {  # any name can be used
          # your second db settings here
        }
      }
      
    • Define your models using Django ORM, and don’t forget to set managed = False and the correct table_name in the models’ Meta.
    • Query your second database with ModelInSecondDb.objects.using('second').all()
    • Optionally, add a database router class that would automatically direct all queries for these models to your second db.

0👍

You can define another database configurations in django settings like:

DATABASES = {
  'default': {},
  'another_db' : {
    ...
  }
}

and in django ORM you can do like :

another_db_table.objects.using('another_db').all()

check out django docs here

Leave a comment