You can do this with son manipulators. Here's an example:
import pprint
import pymongo
from pymongo.son_manipulator import SONManipulator
class MyWrapper(dict):
def __init__(self, *args, **kwargs):
super(MyWrapper, self).__init__(*args, **kwargs)
def what_am_i(self):
return "I'm an instance of MyWrapper!"
class MyManipulator(SONManipulator):
def transform_outgoing(self, son, collection):
return MyWrapper(son)
c = pymongo.Connection()
db = c.foo
db.add_son_manipulator(MyManipulator())
db.bar.remove()
db.bar.insert({'foo': {'bar': 'baz'}})
doc = db.bar.find_one()
assert isinstance(doc, MyWrapper)
print type(doc)
pprint.pprint(doc)
print doc.what_am_i()
On Feb 14, 1:25 am, Paul-Olivier Dehaye <
pauloliv...@gmail.com> wrote:
> Hi
> I have a class MyModel that can directly be instantiated from json records
> of a specific shape. For instance, MyModel might require a list with
> exactly 3 components whose second component is a dict with specific
> key-type pairings, the other entries being free (but all types that occur
> are always subclasses of valid json types). It then returns the same json
> record, but with corresponding entries "upgraded" to the appropriate
> subclasses.
> As a consequence, MyModel() would not work for instance, since MyModel is
> not passed such a dictionary here.
> I was hoping I could use the as_class = MyModel option to basically create
> for myself a low-level ODM, with all searches, sorting and so on handled by
> pymongo, but immediate conversion to MyModel as it goes out of the database
> (seems natural to me, no?).
> Unfortunately, it hiccups here:
https://github.com/mongodb/mongo-python-driver/blob/master/bson/__ini...