from bson.objectid import ObjectId
class CustomObjectId(CustomType):
mongo_type = ObjectId # optional, just for more validation
python_type = str
init_type = None # optional, fill the first empty value
def to_bson(self, value):
"""convert type to a mongodb type"""
return ObjectId(value)
def to_python(self, value):
"""convert type to a python type"""
return str(value)
def validate(self, value, path):
"""OPTIONAL : useful to add a validation layer"""
if value is not None:
pass # ... do something here
2 回答
python中获取对象字符串表示的标准方法是使用
str
内置函数:试试这个:
顺便说一句,您可以使用MongoKit来处理特殊的bson数据结构 .
这个自定义ObjectId可以将bson
ObjectId
变为pythonstr
.有关更多信息,请访问http://mongokit.readthedocs.org/mapper.html#the-structure .