現在、MongoEngineはmongodbの拡張json構文のみをサポートしているため、これは直接サポートされていません。
mongoengineが内部で行うのは、pymongoのjson_utils
を使用することだけです。 データをダンプします。明示的に使用できない理由はありません。例:
from bson import json_util
class Inbox(db.Document):
from_user = db.ReferenceField(User, required=True)
subject = db.StringField(max_length=255, required=True)
created_at = db.DateTimeField(default=datetime.now)
messages = db.ListField(db.EmbeddedDocumentField(Message))
def to_json(self):
data = self.to_mongo() // get the pymongo representation of the document
data["from_user"] = {"User": {"username": self.from_user.username}}
return json_util.dumps(data)
User.drop_collection()
...
Inbox.drop_collection()
ross = User(username="Ross").save()
Inbox(from_user=ross, subject="Mongoengine should make json easier").save()
doc = Inbox.objects.only('from_user', 'subject', 'created_at').get()
print doc.to_json()
{"_id": {"$oid": "538c3d71c3d384172fe35393"},
"from_user": {"User": {"username": "Ross"}},
"subject": "Mongoengine should make json easier",
"created_at": {"$date": 1401703297198}, "messages": []}
更新
カスタムクエリセットの例:
from bson import json_util
class CustomQuerySet(QuerySet):
def to_json(self):
return "[%s]" % (",".join([doc.to_json() for doc in self]))
class Inbox(Document):
from_user = ReferenceField(User, required=True)
subject = StringField(max_length=255, required=True)
created_at = DateTimeField(default=datetime.now)
messages = ListField(EmbeddedDocumentField(Message))
meta = {'queryset_class': CustomQuerySet}
def to_json(self):
data = self.to_mongo()
data["from_user"] = {"User": {"username": self.from_user.username}}
return json_util.dumps(data)
...
ipdb> Inbox.objects.only('from_user', 'subject', 'created_at').to_json()
'[{"_id": {"$oid": "538d84cbc3d3843eeeb5dbbe"},
"from_user": {"User": {"username": "Ross"}},
"subject": "Mongoengine should make json easier",
"created_at": {"$date": 1401787099246}, "messages": []}]'