Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know current name of the database in Django?

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

like image 351
Artem Mezhenin Avatar asked Apr 11 '12 07:04

Artem Mezhenin


People also ask

What is Django database called?

Django officially supports the following databases: PostgreSQL. MariaDB. MySQL.

Where is the database in Django?

In the settings.py file, there is a variable called DATABASES . It is a dict, and one of its keys is default , which maps to another dict. This sub-dict has a key, NAME , which has the path of the SQLite database.


2 Answers

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.

like image 112
Rems Avatar answered Sep 30 '22 17:09

Rems


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.

like image 32
naktinis Avatar answered Sep 30 '22 18:09

naktinis