我有一个带有 ReferenceFields 列表的类,如下所示:
class MyClass(db.Document):
meta = {
...
}
something: ReferenceField(OtherClass, required=True, reverse_delete_rule=CASCADE)
otherthings = SortedListField(ReferenceField(AnotherClass), ordering='id')
我可以创建一个MyClass对象,它可以很好地运行:
>>> h
<MyClass: MyClass object>
>>> h.id
ObjectId('54cf8f91b0ab4a2b7c5a71b6')
>>> h.otherthings
[<AnotherClass: AnotherClass(pk=54cf8fbeb0ab4a2d35631cf0)>, <AnotherClass: AnotherClass(pk=54cf8fc7b0ab4a2bd7abfe78)>, <AnotherClass: AnotherClass(pk=54cf8fd3b0ab4a2bda781fd5)>, <AnotherClass: AnotherClass(pk=54cf8fd3b0ab4a2b7c5a71b9)>, <AnotherClass: AnotherClass(pk=54cf8ffbb0ab4a2fa167f335)>, <AnotherClass: AnotherClass(pk=54cf9001b0ab4a2fcc6ae982)>, <AnotherClass: AnotherClass(pk=54cf9001b0ab4a2fcc6ae983)>, <AnotherClass: AnotherClass(pk=54cf9001b0ab4a3170f6cc00)>, <AnotherClass: AnotherClass(pk=54cf9002b0ab4a31566e9837)>, <AnotherClass: AnotherClass(pk=54cf9002b0ab4a2ffc13b055)>]
但是我需要通过Flask返回它,所以我正在尝试运行 to_json()但是它不起作用:
>>> h.to_json()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/lala/whatever/.virtualenvs/whatever/local/lib/python2.7/site-packages/mongoengine/base/document.py", line 327, in to_json
return json_util.dumps(self.to_mongo(), *args, **kwargs)
File "/home/lala/whatever/.virtualenvs/whatever/local/lib/python2.7/site-packages/mongoengine/base/document.py", line 255, in to_mongo
value = field.to_mongo(value)
File "/home/lala/whatever/.virtualenvs/whatever/local/lib/python2.7/site-packages/mongoengine/fields.py", line 739, in to_mongo
reverse=self._order_reverse)
TypeError: 'ObjectId' object has no attribute '__getitem__'
我做错了什么?我希望答案如下:
>>> h.to_json()
'{"_id": {"$oid": "54cf8f91b0ab4a2b7c5a71b6"}, "something": {"$oid": "54c20742b0ab4a5e4c08f5c7"}, "otherthings": [ "_id": {"$oid": "54cf8fbeb0ab4a2d35631cf0"}, "_id": {"$oid": "54cf8fc7b0ab4a2bd7abfe78"}, "_id": {"$oid": "54cf8fd3b0ab4a2bda781fd5"}, "_id": {"$oid": "54cf8fd3b0ab4a2b7c5a71b9"}, "_id": {"$oid": "54cf8ffbb0ab4a2fa167f335"}, "_id": {"$oid": "54cf9001b0ab4a2fcc6ae982"}, "_id": {"$oid": "54cf9001b0ab4a2fcc6ae983"}, "_id": {"$oid": "54cf9001b0ab4a3170f6cc00"}, "_id": {"$oid": "54cf9002b0ab4a31566e9837"}, "_id": {"$oid": "54cf9002b0ab4a2ffc13b055"} ] }'
而且,如果可以通过 ReferenceFields 提取引用的对象(取消引用?),那就太棒了。
答案 0 :(得分:0)
我找到了一个解决方案,使用来自 Flask 的 json :
json.jsonify(
_id=json.loads(bson.json_util.dumps(h.id)),
something=json.loads(bson.json_util.dumps(h.something.id)),
otherthings=json.loads(bson.json_util.dumps(otherthings))
)
它返回我想要的结构:
{
"_id": {"$oid": "53c92ecad9da48dcc45e0550"},
"something": {"$oid": "53c8cd3414d0e362765e41a2"},
"otherthings": [
{"info":1},
{"info":2},
{"info":3},
{"info":4},
{"info":5},
{"info":6},
{"info":7},
{"info":8},
{"info":9},
{"info":10}
]
}
可以优化/更好地完成吗?