Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top