ReferenceField is not filled by from_json

32 views
Skip to first unread message

Linda Hu

unread,
Oct 1, 2020, 9:01:55 AM10/1/20
to MongoEngine Users
Hello everybody!

I just started working with MongoEngine. My project heavily relies on importing a large amount of data from JSON files. I encountered the problem that, when filling a Document object that has ReferenceFields with the from_json function, the ReferenceFields do not get filled properly (I assume, as the Document object they refer to has not been created yet). This problem does not occur when using EmbeddedDocumentClass. This, however, is not an option for me, as I also need circle references sometimes. 

I want to make something like the following work:

class Human(Document):
    name = StringField()
    best_friend = ReferenceField("Human")

as a class structure should be filled by this JSON file, say scrubs.json,

{
    "name": "JD",
    "best_friend": {
        "name": "Turk"
    }
}

like this:

with open("scrubs.json") as file:
   jd = Human().from_json(file.read())

This works, but

turk = jd.best_friend

throws an error.

So is there a way to somehow recursively create the objects that I am referencing to?

Thank you very, very much!

Cheers,
Linda
Reply all
Reply to author
Forward
0 new messages