python Django-graphene和树形结构输出

yqkkidmi  于 2023-04-04  发布在  Python
关注(0)|答案(1)|浏览(132)

是否可以在django-graphene的帮助下生成以下类型的树结构输出?

"mainMenu": [
    {
        "pageSlug": "page-slug-01",
        "pageTitle": "page-title-01",
        "children": [
            {
                "pageSlug": "sub_page-slug-01",
                "pageTitle": "sub_page-title-01",
                "children": [
                    ...
                ]
            },
            ...
            {
                "pageSlug": "sub_page-slug-N",
                "pageTitle": "sub_page-title-N",
                "children": [
                    ...
                ]
            },
        ]
    },
    ...
    {
        "pageSlug": "page-slug-N",
        "pageTitle": "page-title-N",
        "children": [
            ...
        ]
    },
]

我不知道该怎么形容这些课...

ffx8fchx

ffx8fchx1#

1)创建schema .py

schema.py

import graphene

class MenuItem(graphene.ObjectType):
    page_slug = graphene.String()
    page_title = graphene.String()
    children = graphene.List(lambda: MenuItem)

class Query(graphene.ObjectType):
    main_menu = graphene.List(MenuItem)

def resolve_main_menu(self, info):
    # Code to retrieve the main menu from the database
    main_menu_data = get_main_menu_data()

    def build_menu(menu_data):
        menu_items = []
        for item in menu_data:
            children = item.pop('children', None)
            menu_item = MenuItem(**item)
            if children:
                menu_item.children = build_menu(children)
            menu_items.append(menu_item)
        return menu_items

    return build_menu(main_menu_data['mainMenu'])

schema = graphene.Schema(query=Query)

网址.py

from django.urls import path
from graphene_django.views import GraphQLView
from .schema import schema

urlpatterns = [
    path('graphql', GraphQLView.as_view(graphiql=True, schema=schema)),
]

相关问题