How to know current name of the database in Django?

PythonDjangoUnit Testing

Python Problem Overview


I'm writing tests in my django project. For now, I have two database connections:

(settings.py)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'db_name'
        ...
    },
}

and custom connection to MongoDB:

import sys
from pymongo import Connection
from pymongo.errors import ConnectionFailure
try:
    connection = Connection(host="localhost", port=27017)
    db = connection['db_name']
    print "Connected successfully(Mongo, db_name)"
except ConnectionFailure, e:
    sys.stderr.write("Could not connect to MongoDB: %s" % e)
    sys.exit(1)

and I want to know when my project is running through

python manage.py test myapp

Because when you run tests, django automatically create separate DB(with name like test_db_name), but in this case Mongo will still run with db_name. I tried:

import sys
from pymongo import Connection
from pymongo.errors import ConnectionFailure
from django.db import connections

try:
    connection = Connection(host="localhost", port=27017)
    db_name = connections['default'].settings_dict['NAME']
    db = connection[db_name]
    print "Connected successfully(Mongo, %s)" % (db_name,)
except ConnectionFailure, e:
    sys.stderr.write("Could not connect to MongoDB: %s" % e)
    sys.exit(1)

but it does not work

Python Solutions


Solution 1 - Python

To get the db name with recent Django versions (tried with 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.

Solution 2 - Python

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.

Solution 3 - Python

Tested in django 1.9

Go into the shell.

./manage.py shell

Check your databases.

from django import db
db.connections.databases

Solution 4 - Python

The answer seems to be obsolete.

In django 1.6 you can do:

from django import db
print db.connections.databases

Solution 5 - Python

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

Solution 6 - Python

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!

Solution 7 - Python

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

Solution 8 - Python

In Django >= 1.10 version

Use:

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

Solution 9 - Python

In Django >= 1.11

Use:

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

Solution 10 - Python

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]

Solution 11 - Python

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArtem MezheninView Question on Stackoverflow
Solution 1 - PythonRemsView Answer on Stackoverflow
Solution 2 - PythonnaktinisView Answer on Stackoverflow
Solution 3 - PythonJeff Gu KangView Answer on Stackoverflow
Solution 4 - PythonJan DBView Answer on Stackoverflow
Solution 5 - Pythonuser1237092View Answer on Stackoverflow
Solution 6 - PythonjoshcartmeView Answer on Stackoverflow
Solution 7 - Pythong3rv4View Answer on Stackoverflow
Solution 8 - PythonMohammed YasinView Answer on Stackoverflow
Solution 9 - PythonJuliano BarbosaView Answer on Stackoverflow
Solution 10 - PythonSuperNovaView Answer on Stackoverflow
Solution 11 - PythonSuperNovaView Answer on Stackoverflow