Вопрос

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?

Это было полезно?

Решение

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top