How to check which database is being used in a Django project
Question:
In my Django project I want to use a queryset method that is only available in postgresql, if postgresql is being used.
How can I check the database from settings.DATABASES?
Assuming this structure:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # could be: 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'
My python skills are too weak to traverse that structure of dictionaries =(
Answers:
from django.conf import settings
if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.postgresql_psycopg2':
# happy coding
This gives you the name of database backend configured as default
in settings.DATABASES
:
>>> from django.db import connection
>>> print(connection.vendor)
'sqlite'
In case you have multiple databases configured:
>>> from django.db import connections
>>> print(connections['default'].vendor)
'mysql'
>>> print(connections['reporting'].vendor)
'postgresql'
To improve on the answer posted by Ozgur, in django shell, you need to have parentheses on the call to print:
>>> from django.db import connections
>>> print (connections['default'].vendor)
'mysql'
>>> print (connections['reporting'].vendor)
'postgresql'
In my Django project I want to use a queryset method that is only available in postgresql, if postgresql is being used.
How can I check the database from settings.DATABASES?
Assuming this structure:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # could be: 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'
My python skills are too weak to traverse that structure of dictionaries =(
from django.conf import settings
if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.postgresql_psycopg2':
# happy coding
This gives you the name of database backend configured as default
in settings.DATABASES
:
>>> from django.db import connection
>>> print(connection.vendor)
'sqlite'
In case you have multiple databases configured:
>>> from django.db import connections
>>> print(connections['default'].vendor)
'mysql'
>>> print(connections['reporting'].vendor)
'postgresql'
To improve on the answer posted by Ozgur, in django shell, you need to have parentheses on the call to print:
>>> from django.db import connections
>>> print (connections['default'].vendor)
'mysql'
>>> print (connections['reporting'].vendor)
'postgresql'