Can I query a secondary database from Django without ORM?

Viewed 2409

I need to query a database controlled by another application from my Django application. Ideally I'd also like to modify a few values.

I've configured a secondary database connection from within Django, but because the tables are controlled elsewhere, they don't fit neatly into Django's ORM. I'd rather make simple SQL queries from within my Django application.

Is this possible?

2 Answers

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.

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

Related