我目前正在 Python Django 中查询 MongoDB 对象,如果需要其他属性,则在创建查询时没有遇到任何问题。
但是,我需要修改查询以专门过滤返回一个或未找到对象的 ObjectId。
从我的 Javascript 中,我将 json 数据传递到我的 Django views.py
这是它当前的样子:
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))
*不要混淆 another_id
,有些对象具有相同的 another_id
,但不幸的是必须保持这种状态。这就是为什么我无法查询它的更新,因为它会更新所有重复项。这就是我需要 ObjectId 的原因。
为了检查这里是打印出来的内容:
{u'$oid': u'582fc95bb7abe7943f1a45b2'}
ANOTHER_ID: LTJ1277
因此,我在 views.py
中附加了查询,如下所示:
try:
Line.objects(_id=_id).update(set__geometry=geometry, set__properties=properties)
print("Edited: " + another_id)
except:
print("Unedited.")
但它没有返回任何对象。
So I was wondering if the query itself can't recognize the
$oid
in the json body as"_id" : ObjectId("582fc95bb7abe7943f1a45b2")
?
*编辑:
from bson.objectid import ObjectId
我用以下内容编辑了 views.py
:
_id = line['_id']
print("VALUES: %s" % (_id.get('$oid')))
try:
Line.objects(_id=ObjectId(_id.get('$oid'))).update(set__geometry=geometry, set__properties=properties)
输出:
VALUES: 582fc95bb7abe7943f1a498c
运气不好。仍未查询/未找到。
最佳答案
根据这个Using MongoDB with Django引用网址:
Notice that to access the unique object ID, you use "id" rather than "_id".
我尝试修改代码:
Line.objects(_id=ObjectId(_id.get('$oid'))).update(set__geometry=geometry, set__properties=properties)
至
Line.objects(id=ObjectId(_id.get('$oid'))).update(set__geometry=geometry, set__properties=properties)
...现在工作正常了。为其他可能需要这个问题的人保留这个问题。
关于python - Django 从 json 对象查询 View 中的 MongoDB ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40814699/