1

I wonder where I should initialize my MongoDB connection in my Django projects.

Currently I am initializing the client and db before my view functions in views.py:

import pymongo

from django.conf import settings


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


def some_view(request):
    pass

However I also need to use MongoDB in my models.py in conjunction with Django signals. What do you suggest?

2
  • Is this a main database that you'll be saving to or a separate database that you'll occasionally be reading from? Commented May 3, 2014 at 15:58
  • I will basically use MongoDB to read cached model data. Therefore I am using django signals post_save and post_delete to update MongoDB collections. Commented May 3, 2014 at 16:07

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.