[英]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
和Bar
类型的对象,每个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.