简体   繁体   English

如何返回没有 SQLAlchemy 类型的自定义子项 object

[英]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:我有FooBar类型的对象,每个Bar object 都有一个字段类别(由名称字符串指定)和一个将其链接到Foo类型的 object 的父 ID ...我希望有一个 GQL 模式,可以查询为如下:

{ 
   foo {
      category {
           name
           bar {
                
           }
      }
}

Both Foo and Bar live in the database and can easily be generated as SQLAlchemy objects. Foo 和 Bar 都存在于数据库中,可以很容易地生成为 SQLAlchemy 个对象。 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.但是我不太确定如何编写一个给定 Foo object 的解析器以这种方式返回它的所有类别,以及如何编写一个给定类别的解析器返回该类别中属于 foo 的子对象的所有对象.

So what you need here is a custom defined CategoryType .所以你在这里需要的是一个自定义的CategoryType

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

Then in your FooType然后在你的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()] 


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从graphql中的解析器返回自定义对象? - How to return custom object from resolver in graphql? 如何以突变形式返回自定义对象? - How do I return custom object in a mutation? 如何在 GraphQL 中将复杂的 object 作为标量类型返回? - How to return complex object as scalar type in GraphQL? 石墨烯和 SQLAlchemy:衍生自基础 object 类型 - Graphene and SQLAlchemy: derivate from a base object type 如何使用自定义返回类型在 type-graphql 中创建 GraphQL 查询 - How to create a GraphQL query in type-graphql with a custom return type 如何在GraphQL中返回带有union查询结果的对象类型? - How to return object type with union query results in GraphQL? 如何在Graphql中返回JSON对象并定义JSON类型 - How can I return a JSON object in Graphql and define JSON type 返回自定义 object 到 GraphQL 解析器 - Return custom object to GraphQL resolver 如何在 TypeScript 中使用嵌套对象? 类型“对象”上不存在属性 - How to use nested objects in TypeScript? Property does not exist on type 'object' 我想如何在neo4j graphql js中使用自定义查询返回关系类型 - How do I suppose to do to return a relation type with custom query in neo4j graphql js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM