将mongodb返回对象转换为字典 [英] Convert mongodb return object to dictionary
问题描述
我正在将bottle框架与mongoengine一起使用. 我有一个订单模型:
I'm using the bottle framework together with mongoengine. I have an orders model :
class OrderDetail(Option):
orderDetailsQty = FloatField()
def to_dict(self):
return mongo_to_dict_helper(self)
class Order(Document):
userName = StringField(required=True)
orderDate = DateTimeField()
orderStatus = ListField(EmbeddedDocumentField(Status))
orderDetails = ListField(EmbeddedDocumentField(OrderDetail))
orderComments = ListField(EmbeddedDocumentField(Comment))
isActive = BooleanField()
def to_dict(self):
orderObj = mongo_to_dict_helper(self)
orderDetailList = []
for orderDetail in orderObj["orderDetails"]:
orderDetailList.append(orderDetail.__dict__)
orderObj["OrderDetails"] = orderDetailList
return (self)
查询mongodb时,我得到一个对象,然后使用以下函数将其转换为字典:
When mongodb is queried I get an object which is then converted in to a dict by using the following function :
def mongo_to_dict_helper(obj):
return_data = []
for field_name in obj._fields:
if field_name in ("id",):
continue
data = obj._data[field_name]
if isinstance(obj._fields[field_name], StringField):
return_data.append((field_name, str(data)))
elif isinstance(obj._fields[field_name], FloatField):
return_data.append((field_name, float(data)))
elif isinstance(obj._fields[field_name], IntField):
return_data.append((field_name, int(data)))
elif isinstance(obj._fields[field_name], ListField):
return_data.append((field_name, int(data)))
else:
# You can define your logic for returning elements
pass
return dict(return_data)
经过长时间的互联网搜索,我发现了此功能.后来发现,在将成员定义为ListField(EmbeddedDocumentField(obj))时,此函数也将失败.
I found this function after a long search in the internet. Later found out that this function also fails while defining a member as the ListField(EmbeddedDocumentField(obj)).
我还尝试编写一个条件来捕获EmbeddedDocumentField的特定情况:
I also tried writing a condition for catching the specific case of EmbeddedDocumentField :
elif isinstance(obj._fields[field_name], EmbeddedDocumentField):
return_data.append(mongo_to_dict_helper(data))
但这也没有任何好处.
任何人都有解决此问题的方法吗?
Anyone have a workaround for this issue ?
推荐答案
仅使用对象的to_mongo
方法将其转换为字典该怎么办?
What about just using to_mongo
method of an object to convert it to a dict?
object.to_mongo()
这篇关于将mongodb返回对象转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!