我正在使用ODM库,并且当它们相关时,我将文档定义为同一模块中的类。我遇到了一个循环依赖问题,因为我之前在Python中没有遇到过这个问题,我不知道如何告知类别彼此的存在。例如:
''' docs.py '''
from mongoengine import Document
from mongoengine.fields import StringField, ReferenceField, ListField
class Base(Document):
some_field = StringField()
class Foo(Base):
other_field = StringField()
another_field = ReferenceField(Bar)
class Bar(Base):
other_field = StringField()
another_field = ListField(ReferenceField(Foo))
目前,Python将抛出NameError
,因为当解释器在类Bar
中获取对文件的引用时,未定义Foo
。我如何告诉Python不要担心,并且类定义将很快出现?
答案 0 :(得分:5)
ReferenceField
也接受类名。
another_field = ReferenceField('Bar')