1

I am currently working on querying MongoDB objects in Python Django and had no trouble in creating queries if it's the other attributes needed.

However I need to modify my queries to specifically filter through the ObjectIds returning one or no object found.

From my Javascript I am passing a json data to my Django views.py here's how it currently looks like:

def update(request):
   #AJAX data
   line = json.loads(request.body)

   _id = line['_id']
   print("OBJECT_ID: %s" % (_id))
   another_id = line['another_id']
   print("ANOTHER_ID: %s" % (another_id))

*Don't confuse the another_id, there are objects that has the same another_id s and unfortunately has to remain like that. That's why I can't query it for update since it will update all duplicates. This is the reason why I need the ObjectId.

For checking here's what it prints out:

{u'$oid': u'582fc95bb7abe7943f1a45b2'}
ANOTHER_ID: LTJ1277

Therefore I appended the query in views.py like this:

    try:
       Line.objects(_id=_id).update(set__geometry=geometry, set__properties=properties)
       print("Edited: " + another_id)
    except:
       print("Unedited.")

But it didn't return any object.

So I was wondering if the query itself can't recognize the $oidin the json body as "_id" : ObjectId("582fc95bb7abe7943f1a45b2")?

*Edit:

from bson.objectid import ObjectId

where I edited my views.py with:

    _id = line['_id']
    print("VALUES: %s" % (_id.get('$oid')))

    try:
    Line.objects(_id=ObjectId(_id.get('$oid'))).update(set__geometry=geometry, set__properties=properties)

Output:

VALUES: 582fc95bb7abe7943f1a498c

No luck. Still not querying/not found.

1 Answer 1

2

According to this Using MongoDB with Django reference site:

Notice that to access the unique object ID, you use "id" rather than "_id".

I tried revising the code from:

Line.objects(_id=ObjectId(_id.get('$oid'))).update(set__geometry=geometry, set__properties=properties)

to

Line.objects(id=ObjectId(_id.get('$oid'))).update(set__geometry=geometry, set__properties=properties)

...And it now works fine. Keeping this question for others who might need this.

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

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.