graphqlgraphene-pythongraphene-sqlalchemy

How to return custom child object that does not have a SQLAlchemy type


I have objects of type Foo and Bar, each Bar object has a field category (specified by a name string) and a parent id linking it to an object of type Foo ... I wish to have a GQL schema which can be queried as follows:

{ 
   foo {
      category {
           name
           bar {
                
           }
      }
}

Both Foo and Bar live in the database and can easily be generated as SQLAlchemy objects. However I'm not quite sure how to write a resolver which given a Foo object returns all the categories for it in this fashion, and how to write a resolver which given the category returns all the objects that are a child of foo in that category.


Solution

  • So what you need here is a custom defined CategoryType.

    class CategoryType(graphene.ObjectType):
        name = graphene.String()
        bars = graphene.List(BarType)
    

    Then in your FooType

    class FooType(SQLAlchemyObjectType):
        class Meta:
            model = Foo
    
        categories = graphene.List(CategoryType)
    
        def resolve_categories(self, info):
            organized = {}
            for bar in self.bars:
                if (bar.category in organized):
                    organized[bar.category].append(bar)
                else:
                    organized[bar.category] = [bar]
    
            return [{ "name": name, "bars": bars } for name, bars in organized.items()]