سؤال

I have a mapped class in 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)

Now, I want to do a simple query to it as

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

But it doesn't work. Documentation is not quite clear about it. I know that in mongodb shell we have to wrap the id in an ObjectId object, but I can't get it to work in Python

هل كانت مفيدة؟

المحلول

You should try the query with ObjectId

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

With naked 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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top