Graphene / GraphQL查找特定的列值

时间:2019-07-07 08:49:42

标签: django flask graphql graphene-python graphene-sqlalchemy

由于某些原因,我无法弄清楚如何在我的 SQLAlchemy 数据库中找到特定的数据。

graphene-python documentation中,它只是执行此查询以匹配ID(它是一个字符串):

book(id: "Qm9vazow") {
    id
    title
}

现在这是我的BookSchema的Flask-Graphene-SQLAlchemy代码,我想找到一个特定的标题而不是ID:

class BookModel(db.Model):
    __table__ = db.Model.metadata.tables['books_book']

# Schema Object
class BookSchema(SQLAlchemyObjectType):
    class Meta:
        model = BookModel
        interfaces = (relay.Node, )

# Connection
class BookConnection(relay.Connection):
    class Meta:
        node = BookSchema

# GraphQL query
class Query(graphene.ObjectType):
    node = relay.Node.Field()
    allBooks = SQLAlchemyConnectionField(BookConnection)


schema = graphene.Schema(query=Query, types=[BookSchema])

运行此查询时,一切正常,并返回3个书名:

{
    "query": "{ allBooks(first: 3) { edges { node { title } } } }"
}

但是,一旦我尝试匹配特定的标题,它就会停止工作。例如:

# I tried all these queries, none worked
1. { allBooks(title: \"some book title\") { edges { node { title } } } }
2. { allBooks(title: \"some book title\") { title }
3. { allBooks(title: 'some book title') { edges { node { title } } } }

错误:"Unknown argument \"title\" on field \"allBooks\" of type \"Query\"."

我必须犯一个我没有看到的小错误,但是我无法弄清楚。我花了几个小时试图弄清楚这个问题。

问题:如何匹配标题并使其返回对象?我在做什么错了?

1 个答案:

答案 0 :(得分:0)

想通了!请参见下面的更改。

class Query(graphene.ObjectType):
    node = relay.Node.Field()
    all_books = SQLAlchemyConnectionField(BookConnection)

    # Added this
    find_book = graphene.Field(BookSchema, title = graphene.String())

    def resolve_find_book(self, info, title):
      query = BookSchema.get_query(info)
      return query.filter(BookModel.title == title).first()

我的GraphQL查询如下:

{
    "query": "{ findBook(title: \"some book title\") { title } }"
}

希望这对以后的人有帮助!