37

I'm doing some "extra" queries in Django that need to work on both sqlite and postgres. The syntax of these queries varies between backend but I have no way of figuring out if I'm sending my queries to either postgres or sqlite.

Is there a way to get the current database adapter so I can branch my code and send the right query for the active database server?

3
  • queries accept the keyword 'using', where you can select the db where the queries should be performed on. docs.djangoproject.com/en/dev/topics/db/multi-db
    – Jingo
    Sep 17, 2013 at 10:40
  • 2
    the current database always is DATABASES['default'] in settings.py no ? And DATABASES['default']['ENGINE'] should contain the engine type.
    – Ricola3D
    Sep 17, 2013 at 11:00
  • I was thinking of a real API instead of checking the settings (like the one proposed in ticket 18332). Checking settings works fine though, would like to mark that as an answer but I can't :)
    – jaap3
    Sep 17, 2013 at 11:27

1 Answer 1

75

OK, so there's two ways of doing it, as @Ricola3D said there's the option of checking settings.DATABASES['default']['ENGINE']:

>>> from django.conf import settings
>>> settings.DATABASES['default']['ENGINE']
'django.db.backends.sqlite3' or 'django.db.backends.postgresql_psycopg2'

But there's also an (undocumented) vendor property on a connection:

>>> from django.db import connection
>>> connection.vendor
'postgresql' or 'sqlite'

Either way works. I personally prefer connection.vendor as it looks prettier :)

1
  • Careful when running tests: with a different DB type: settings.DATABASES['default']['ENGINE'] will still point at the non-testing DB. So connection.vendor (or, if you have multiple DBs) connections[db_name].vendor is much better, I think
    – farialima
    Dec 26, 2021 at 18:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.