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
Django officially supports the following databases: PostgreSQL. MariaDB. MySQL.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With