gpt4 book ai didi

python - 如何通过_id在ming中查找?

转载 作者:可可西里 更新时间:2023-11-01 10:33:09 25 4
gpt4 key购买 nike

我在 ming 中有一个映射类

from ming import Session, create_datastore
from ming import schema
from ming.odm import ODMSession
from ming.odm.mapper import MapperExtension
from ming.odm.property import ForeignIdProperty
from ming.odm.property import FieldProperty, RelationProperty
from ming.odm.declarative import MappedClass
import config

bind = create_datastore(config.DATABASE_NAME)
session = Session(bind)
odm_session = ODMSession(doc_session=session)


class Document(MappedClass):

class __mongometa__:
session = odm_session
name = 'document'

_id = FieldProperty(schema.ObjectId)

现在,我想对它做一个简单的查询

Document.query.get(_id="51e46f782b5f9411144f0efe")

但它不起作用。文档对此不是很清楚。我知道在 mongodb shell 中我们必须将 id 包装在一个 ObjectId 对象中,但我无法让它在 Python 中工作

最佳答案

您应该尝试使用 ObjectId 进行查询

from bson.objectid import ObjectId
Document.query.get(_id=ObjectId('51e46f782b5f9411144f0efe'))

裸体pymongo

from bson.objectid import ObjectId
from pymongo import Connection
connection = Connection()
db = connection['lenin']
collection = db.document
collection.find_one({'_id': '51e35ee82e3817732b7bf3c1'}) # returns None
collection.find_one({'_id': ObjectId('51e35ee82e3817732b7bf3c1')}) # returns the object

关于python - 如何通过_id在ming中查找?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17665480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com