I øjeblikket understøttes dette ikke direkte, da MongoEngine kun understøtter mongodbs udvidede json-syntaks.
Alt hvad mongoengine gør under coveret er at bruge pymongos json_utils
at dumpe dataene. Der er ingen grund til, at du ikke kan bruge det eksplicit, f.eks.:
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": []}
Opdateret
Eksempel med tilpasset forespørgselssæt:
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": []}]'