[Django]-How to know current name of the database in Django?

103πŸ‘

βœ…

To get the db name with recent Django versions (1.8+):

from django.db import connection
db_name = connection.settings_dict['NAME']
# Or alternatively
# db_name = connection.get_connection_params()['db']

Be mindful of reading this value after initialization, so that it has the correct value when running unit tests.

πŸ‘€Rems

18πŸ‘

Update: the answer below is for older Django versions. For up to date approach check the answer by Rems:

from django.db import connection
db_name = connection.settings_dict['NAME']

In older Django versions, you can check it in db.settings:

from django import db
db.settings.DATABASES['default']['NAME']

To see the database used to fetch a specific object you can do:

object._state.db

This will give you the database key in config, such as β€˜default’, so if you have multiple databases in config you can check the right one.

When you run tests, db.settings should be updated to contain the test-specific database name.

πŸ‘€naktinis

16πŸ‘

Tested in django 1.9

Go into the shell.

./manage.py shell

Check your databases.

from django import db
db.connections.databases
πŸ‘€Jeff Gu Kang

15πŸ‘

The answer seems to be obsolete.

In django 1.6 you can do:

from django import db
print db.connections.databases
πŸ‘€Jan DB

13πŸ‘

IMO, the best way to do this, is the following undocumented django function:

>>> from django.db import connection
>>> connection.vendor
'postgresql' or 'sqlite'

Thx to: https://stackoverflow.com/a/18849255/1237092

πŸ‘€user1237092

2πŸ‘

Try putting the following in your settings file:

import sys

management_command = sys.argv[1] if len(sys.argv) > 1 else ""

TESTING = management_command.startswith("test")

If TESTING is true you are running with python manage.py test myapp.

edit: You probably could put that anywhere, not necessarily your settings file. Give it a go and see how it works!

πŸ‘€joshcartme

2πŸ‘

What worked excellent for me (the dictionary was empty in my case because I’m using a read_default_file file in settings.py) is just executing the following SQL query

SELECT DATABASE()
πŸ‘€g3rv4

2πŸ‘

In Django >= 1.10 version

Use:

from django.conf import settings
db_name = settings.DATABASES['default']['NAME']

1πŸ‘

In Django >= 1.11

Use:

from django import db
db_name = db.utils.settings.DATABASES['default']['NAME']

1πŸ‘

In case of mysql, raw query through django, can be a solution too.

from django.db import connection
cursor = connection.cursor()
cursor.execute('select database()')
row = cursor.fetchone()

print row[0]
πŸ‘€SuperNova

1πŸ‘

To get database conf and NAME, you can use any of the models in any app

from someapp.models import ExampleModels

current_DB = ExampleModels.objects.db
print (current_DB)
πŸ‘€SuperNova

Leave a comment