7

i am new to mongodb and django . i setup all the models and urls.py in django. but its time to retrieve the information of database on view page. my database looks like:

{
"_id": {
    "$oid": "52221778633a610c58c131e6"
},
"text": "just",
"tags": [
    "mongo",
    "django"
],
"comments": [],
"title": "hello" }

database name:events collection name:polls_post

my urls.py is look like:

from django.conf.urls.defaults import patterns, include, url
from django.views.generic import ListView, DetailView
from polls.models import Post

urlpatterns = patterns('',
     url(r'^time/$','polls.views.current_datetime'),
     url(r'^events/$','polls.views.events'),
)

my views.py looks like:

from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

def events(request):
    html = "<html><body>title is:<h1></h1></body></html>" 
    return HttpResponse(html)    

so, how will we fetch text, title and comments from database so that it can be shown on web page ?

3 Answers 3

4

To have access to database, django has something called models. This is a full fletched ORM to abstract nuts and bolts of underlying database. Django's ORM is fully functional for Relational DBs. Mongo being NoSQL, we have to look for other options. The most widely used ORM's for MongoDB include Mongokit and MongoEngine. These are the wrappers built on top of Pymongo. For simplicity, here is a short code snippet for fetching data from mongoDB using pymongo.

from pymongo import Connection

server="localhost"
port = 27017
#Establish a connection with mongo instance.
conn = Connection(server,port)

To get a single document from collection, use find_one.

poll = conn.events.polls_post.find_one({},{"title" : 1}) #first parameter is the query, second one is the projection.
print "Title : ", poll['title']

To get all documents from collection, use find.

polls = conn.events.polls_post.find({},{"title" : 1})#first parameter is the query, second one is the projection.
for poll in polls:
    print "Title : ",poll['title']

If you would like to use Django's Non Relational Engine, you can write:

from models import Post 
posts = Post.objects.all() 
for post in posts: 
    print post.title

This assumes you have already created a model class in models.py: Something like this:

class Post(models.Model):
    created_on = models.DateTimeField(auto_now_add=True, null=True)
    title = models.CharField()
    text = models.TextField()
    tags = ListField()

For more useful stuff, checkout: pymongo and MognoDB. To use Django's Non relational Engine checkout : Django Non Relational Engine

Thanks!

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

5 Comments

thanx for your response but is there any way to fetch data from database without using "pymongo" as i was taking help from here and probably they haven't use third party ORM. i only want some kind of query so that data can be displayed on web page
@user2511142 that code is from a third-party library, namely django-mongodb-engine, as it's on the documentation site for that very library.
Try out : from models import Post posts = Post.objects.all() for post in posts: print post.title
BTW, Pymongo is the official python mongo engine to deal with MongoDB. Django's mongoDB engine internally uses the same. So, you are not using any third party library as far as pymongo is concerned.
@user2511142 Update answer to include this change.
0

This is used to show the list of all databases in mongodb to which ip we connected in django application ***** This worked for me *******

from django.db import connection import pymongo

        mongo1 = pymongo.Connection('127.0.0.1')

        print mongo1.database_names()

Comments

0
In Views:

def user_add(request):
    if request.method == "POST":
     # do save process
    else:
      #brand_list = UserModule.objects.all()
      brand_list = UserModule.objects.values('department','designation','division')
      return render_to_response('useradd.html', {'brand_list': brand_list},
                          context_instance=RequestContext(request))

In Html page

      <select name="designation" class="form-control"  id="designation">
          <option value="Z">Select a designation</option>
              {% for brand in brand_list %}
                   <option>

               {%for i in brand.designation%}
                   {{ i }}
               {%endfor%}

              </option>
                {% endfor %}
        </select>

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.