[Answered ]-Where to initialize MongoDB connection in Django projects?

1👍

Maybe settings.py? Or even root __init__.py? Then you can import client and db everywhere you need it.

1👍

I’ve decided to use project/mongodb.py (same folder as settings.py)

import pymongo

from django.conf import settings


client = pymongo.MongoClient(settings.MONGO_URI)
mongodb = client.get_default_database()

I am using two different settings files for local and production. Therefore, this approach makes it possible to use environment dependent settings, while enabling me to access mongodb variable from anywhere in the project.

Leave a comment