Python 如何使用ReferenceField的SortedListField执行.to_json()

Python 如何使用ReferenceField的SortedListField执行.to_json(),python,mongoengine,Python,Mongoengine,我有一个类,有一个参考字段列表,类似这样: class MyClass(db.Document): meta = { ... } something: ReferenceField(OtherClass, required=True, reverse_delete_rule=CASCADE) otherthings = SortedListField(ReferenceField(AnotherClass), ordering='id') 我可以

我有一个类,有一个参考字段列表,类似这样:

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)>]

而且,如果可以通过ReferenceFields提取引用对象(解除引用?),那就太好了。

我从Flask中找到了一个使用json的解决方案:

它返回我想要的结构:

{
    "_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}
    ]
}
它可以优化/更好地完成吗

>>> 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"} ] }'
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}
    ]
}