简体   繁体   中英

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.

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()] 


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM