2013-04-04 76 views
0

該代碼炸彈:在MongoEngine中使用reverse_delete_rule時,如何使用循環或前向ReferenceField?

from mongoengine import * 

class Employee(Document): 
    name = StringField() 
    boss = ReferenceField("Employee", reverse_delete_rule = NULLIFY) 

繼承人的例外:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "[…]/mongoengine/base.py", line 791, in __new__ 
    new_class = super_new(cls, name, bases, attrs) 
    File "[…]/mongoengine/base.py", line 630, in __new__ 
    f.document_type.register_delete_rule(new_class, 
    File "[…]/mongoengine/fields.py", line 757, in document_type 
    self.document_type_obj = get_document(self.document_type_obj) 
    File "[…]/mongoengine/base.py", line 136, in get_document 
    """.strip() % name) 
mongoengine.base.NotRegistered: `Employee` has not been registered 
in the document registry. 
Importing the document class automatically registers it, has it 
been imported? 

卸下reverse_delete_rule解決了這個問題,但我想有此規則。

我想這一點,和它的作品,但它確實看起來像廢話,我擔心可能會有不好的副作用(到目前爲止,我還沒有看到任何,雖然):

from mongoengine import * 

class Employee(Document): 
    pass # required for the reverse_delete_rule to work on the boss field, 
     # because the Employee class needs to exist. 

class Employee(Document): 
    name = StringField() 
    boss = ReferenceField("Employee", reverse_delete_rule = NULLIFY) 

有任何想法嗎?這不應該被視爲MongoEngine中的錯誤嗎?

回答

4

嘗試使用'self'代替'Employee'

from mongoengine import * 

class Employee(Document): 
    name = StringField() 
    boss = ReferenceField("self", reverse_delete_rule = NULLIFY) 

查看詳情:https://mongoengine-odm.readthedocs.org/en/latest/guide/defining-documents.html#reference-fields

+0

謝謝,它的作品!這解決了「自我」問題,而不是「前進」問題(如果我需要引用稍後定義的類)? – MiniQuark 2013-04-04 14:36:50

+0

對於這種情況,可能更好地使用'GenericReferenceField'(https://mongoengine-odm.readthedocs.org/en/latest/guide/defining-documents.html#generic-reference-fields)。 – tbicr 2013-04-04 15:36:24