Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a custom query using django-nonrel and mongodb

Is there a recommended way to make a custom query to mongodb using django nonrel?

I have an entire site set up and running well, now I am just adding in some geospatial indexing and queries, and wanted to know if for geospatial queries there is already support or if there is a best practice way to do it using a custom made query?

like image 643
Tom Gruner Avatar asked Apr 06 '11 17:04

Tom Gruner


1 Answers

I found one answer to this question, let me now if there is a better one.

As documented here assign your objects to the MongoDBManager - http://django-mongodb-engine.github.com/mongodb-engine/cool-stuff.html#included-mongodb-batteries

from django_mongodb_engine.contrib import MongoDBManager

class MyModel(models.Model):
    objects = MongoDBManager()

Then you can do raw queries like this:

MyModel.objects.raw_query({'loc' : {'$near' : [50,50]}})

A different approach I guess would be to go directly to pymongo: http://api.mongodb.org/python/1.10%2B/examples/geo.html

Finally I ended up with this query:

nearest = MyModel.objects.raw_query(
    {'loc' : {
         '$within' :{ #within .05 degrees of lat/lon
                    '$center' : [{'long' : long,'lat' : lat}, .05]
                    }
      })[:10] #get up to 10 results
like image 132
Tom Gruner Avatar answered Oct 17 '22 20:10

Tom Gruner