python - Django 从 json 对象查询 View 中的 MongoDB ObjectId

标签 python django mongodb mongoengine

我目前正在 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 $oidin 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/

相关文章:

缺少 Django 管理 CSS

python - 为什么 Q 对象返回重复的结果?

python - 如何在同一个Python程序中将Python变量传递给bash代码?

python - 如何在两个远程数据库之间同步 MySQL 数据库(无需 MySQL 数据库复制技术)

python - 如何从 django Rest Frameworks 基于类的创建 View 将对象添加到我的用户配置文件上的 M2M 字段?

C# 使用 GroupBy 查询 MongoDB

mongodb - 展平 mongoDB 中的嵌套 JSON 结构

node.js - 架构配置无效 : `...` is not a valid type at path `ref`

python : Different behaviour of DatetimeIndex while plotting line and bar plots using DataFrame

python - 某些字符(商标符号等)无法写入文件但可在屏幕上打印