Question

At the moment, I am trying to return simple queries from a database (MongoDB at the moment, but I have used MSSQL 2008 in the past) via a Django application.

My question is surrounding the general Django database setup. For instance, if I am using pymongo on the back-end to set up a connection and return the collection for which I am looking, what are django-nonrel and mongodb-engine really doing? If I returned the queried data (in views.py, for instance) and rendered this through one of my templates, is there a disadvantage to this over setting up the database in settings.py?

Here is how I currently return queried data in views.py:

from django.shortcuts import render_to_response
from pymongo import MongoClient

def bar(request):
    client = MongoClient()
    db = client['myDB']
    collection = db.myCollection.find({"date":"2013-10-23"})
    return render_to_response("index.html", {"returnedData" : collections})
Was it helpful?

Solution

The disadvantage of your code is that you pay the cost of setting up a MongoClient and establishing a connection to the server with every request. You should only create a single MongoClient and use it throughout the lifetime of your application. If you test the performance of your example code and compare it to the performance of creating a single MongoClient once, when your application starts, I expect you'll see that your code is orders of magnitude slower.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top