How to know current name of the database in Django?
Question:
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
Answers:
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!
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.
IMO, the best way to do this, is the following undocumented django function:
>>> from django.db import connection
>>> connection.vendor
'postgresql' or 'sqlite'
The answer seems to be obsolete.
In django 1.6 you can do:
from django import db
print db.connections.databases
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.
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()
Tested in django 1.9
Go into the shell.
./manage.py shell
Check your databases.
from django import db
db.connections.databases
In Django >= 1.10 version
Use:
from django.conf import settings
db_name = settings.DATABASES['default']['NAME']
In Django >= 1.11
Use:
from django import db
db_name = db.utils.settings.DATABASES['default']['NAME']
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]
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)
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
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!
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.
IMO, the best way to do this, is the following undocumented django function:
>>> from django.db import connection
>>> connection.vendor
'postgresql' or 'sqlite'
The answer seems to be obsolete.
In django 1.6 you can do:
from django import db
print db.connections.databases
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.
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()
Tested in django 1.9
Go into the shell.
./manage.py shell
Check your databases.
from django import db
db.connections.databases
In Django >= 1.10 version
Use:
from django.conf import settings
db_name = settings.DATABASES['default']['NAME']
In Django >= 1.11
Use:
from django import db
db_name = db.utils.settings.DATABASES['default']['NAME']
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]
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)