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 =(

Asked By: 43Tesseracts

||

Answers:

from django.conf import settings

if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.postgresql_psycopg2':
   # happy coding
Answered By: Geo Jacob

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'
Answered By: Ozgur Vatansever

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'
Answered By: Collin Rukundo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.