1

出于某种原因,我无法弄清楚如何在我的SQLAlchemy数据库中简单地找到特定的数据。

graphene-python 文档中,它只是简单地执行此查询以匹配 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\"."

我一定犯了一个我没有看到的小错误,但我无法弄清楚。我花了几个小时试图弄清楚这一点。

问题:如何匹配标题并让它返回对象?我究竟做错了什么?

4

1 回答 1

3

弄清楚了!请参阅下面的更改。

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 } }"
}

希望这对将来的人有所帮助!

于 2019-07-07T09:50:36.010 回答