代码之家  ›  专栏  ›  技术社区  ›  MiniQuark

在MongoEngine中使用reverse_delete_rule时,如何拥有循环或正向ReferenceField?

  •  1
  • MiniQuark  · 技术社区  · 11 年前

    这个代码轰炸:

    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中的一个bug吗?

    1 回复  |  直到 11 年前
        1
  •  7
  •   tbicr    11 年前

    尝试使用 '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 .