58

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

Artem Mezhenin
  • 5,539
  • 6
  • 32
  • 51

11 Answers11

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.

Nils
  • 5,612
  • 4
  • 34
  • 37
Rems
  • 4,837
  • 3
  • 27
  • 24
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
  • 3,957
  • 3
  • 36
  • 52
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
  • 4,749
  • 2
  • 36
  • 44
15

The answer seems to be obsolete.

In django 1.6 you can do:

from django import db
print db.connections.databases
Jan DB
  • 355
  • 2
  • 6
12

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

Community
  • 1
  • 1
user1237092
  • 474
  • 4
  • 7
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,717
  • 1
  • 22
  • 34
  • I'm glad it works. In what way would you want a solution to be more elegant? – joshcartme Apr 11 '12 at 16:57
  • I thought there is some variable/function **in** django from which I can grab current database settings. – Artem Mezhenin Apr 12 '12 at 05:13
  • Gotcha, I don't know of one, but maybe someone else will. – joshcartme Apr 12 '12 at 16:26
  • There are many possible ways to be running tests, e.g. "manage.py jenkins", or "jtest", or you could have written your own test runner. You could add detection for all of these commands, but I'd worry that six months from now, you'll forget one, and then your tests will suddenly start blowing away your production database. Not a good day. – Jonathan Hartley Apr 18 '12 at 14:39
  • @Jonathan Hartley That is possible, but the default way to run tests in django is ./manage.py test which is documented here: https://docs.djangoproject.com/en/dev/topics/testing/?from=olddocs#running-tests. I was addressing that. – joshcartme Apr 18 '12 at 16:13
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
  • 19,750
  • 4
  • 36
  • 58
2

In Django >= 1.10 version

Use:

from django.conf import settings
db_name = settings.DATABASES['default']['NAME']
Mohammed Yasin
  • 487
  • 7
  • 12
  • This does not answer the question. Django doesn't update the default name when testing. – Dean Feb 15 '20 at 12:39
1

In Django >= 1.11

Use:

from django import db
db_name = db.utils.settings.DATABASES['default']['NAME']
Floern
  • 33,559
  • 24
  • 104
  • 119
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
  • 25,512
  • 7
  • 93
  • 64
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
  • 25,512
  • 7
  • 93
  • 64
  • how to specify the database, `self.model.component.get_queryset()` using `default` database but I want to use different database connection i.e 'stage' or 'prod', here `self.model.objects.db` returns 'default' – A l w a y s S u n n y Nov 29 '21 at 08:20