pythondjangotreegraphene-python

Django-graphene and tree structure output


Is it possible to make a tree structure output of the following type with the help of 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": [
            ...
        ]
    },
]

I can't figure out how to describe the classes...


Solution

  • 1)Create 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)
    

    urls.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)),
    ]