Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Detect database backend

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?

like image 895
jaap3 Avatar asked Sep 17 '13 09:09

jaap3


1 Answers

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

like image 156
jaap3 Avatar answered Oct 24 '22 10:10

jaap3