0
votes

I am using MongoEngine with Django. In my Django app, I want to create the following embedded document field:

from mongoengine import Document, EmbeddedDocument, StringField, DateTimeField, \
    IntField, EmbeddedDocumentField, BooleanField, ListField

class Person(EmbeddedDocument):
    name = StringField(max_length=200, required=True)
    gender = BooleanField()
    birth_date = DateTimeField()
    death_date = DateTimeField()
    parents = ListField(EmbeddedDocumentField(Person))

I went to test my code in the python shell, and I received the following error:

>>> from models import Person
Traceback (most recent call last):
...(cut for brevity)...
parents = ListField(EmbeddedDocumentField(Person))
NameError: name 'Person' is not defined

In terms of MongoDB schema design, this should be a perfectly valid schema, but MongoEngine doesn't seem to like it. Can someone explain what the issue here is and how to avoid it in a nice way?

1

1 Answers

3
votes

This has nothing to do with MongoEngine; it is a simple Python scoping issue. Person is not defined until the body of the class has finished executing, which means you can't use that name in that class body itself.

MongoEngine does however have a workaround, as the documentation explains; use the string 'self' instead.