MongoEngine递归嵌入

时间:2018-07-29 14:20:52

标签: python flask mongoengine flask-mongoengine

我正在尝试使用mongoengine建模文档,但是我不知道如何进行递归嵌入。例如,我想做这样的事情

class NavigationHelper(EmbeddedDocument):
    name = StringField()
    url = URLField()
    sub_menus = EmbeddedDocumentListField(NavigationHelper)

我将使用它来创建具有无限子菜单可能性的导航树。例如

-menu-1

-sub-menu-1-1

--- sub-menu-1-1-1

--- sub-menu-1-1-2

----子菜单-1-1-2-1

-menu-2

有什么方法可以对此建模?非常感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用一个高级Document和一个列表EmbeddedDocument对其进行建模。

from mongoengine import Document, EmbeddedDocument, StringField, URLField, EmbeddedDocumentListField

# The embeddedDocument of sub-menus
class NavigationSubMenu(EmbeddedDocument):
    name = StringField()
    url = URLField()
    sub_menus = EmbeddedDocumentListField('NavigationSubMenu')


# The document for the main menus
class NavigationMenu(Document):
    name = StringField()
    url = URLField()
    sub_menus = EmbeddedDocumentListField(NavigationSubMenu)

您提供的示例将通过以下方式创建:

docs = [
    NavigationMenu(name='1',
                   sub_menus=[
                       NavigationSubMenu(name='1-1',
                                         sub_menus=[
                                             NavigationSubMenu(name='1-1-1'),
                                             NavigationSubMenu(name='1-1-2',
                                                               sub_menus=[
                                                                   NavigationSubMenu(name='1-1-2-1')
                                                               ])
                                         ])
                   ]
                   ),
    NavigationMenu(name='2')
]

for doc in docs:
    doc.save()

docs = NavigationMenu.objects()

for doc in docs:
    print(doc.name)
    while len(doc.sub_menus) > 0:
        for sub_menu in doc.sub_menus:
            print(sub_menu.name)
            doc = sub_menu

>> 1
>> 1-1
>> 1-1-1
>> 1-1-2
>> 1-1-2-1
>> 2

如果保存此文件,则将获得2个文档。每个高级别NavigationMenu一名。