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?

jaap3
  • 2,696
  • 19
  • 34
  • queries accept the keyword 'using', where you can select the db where the queries should be performed on. https://docs.djangoproject.com/en/dev/topics/db/multi-db/ – Jingo Sep 17 '13 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 '13 at 11:00
  • I was thinking of a real API instead of checking the settings (like the one proposed in [ticket 18332](https://code.djangoproject.com/ticket/18332)). Checking settings works fine though, would like to mark that as an answer but I can't :) – jaap3 Sep 17 '13 at 11:27

1 Answers1

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 :)

jaap3
  • 2,696
  • 19
  • 34
  • 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 '21 at 18:45