简体   繁体   English

Graphene / GraphQL查找特定的列值

[英]Graphene/GraphQL find specific column value

For some reason, I can't figure out how to simply find a specific piece of data in my SQLAlchemy database. 由于某些原因,我无法弄清楚如何在我的SQLAlchemy数据库中简单地查找特定的数据。

In the graphene-python documentation it simply does this query to match the id (which is a string): graphene-python文档中,它只是简单地执行此查询以匹配id(它是一个字符串):

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

Now here's my Flask-Graphene-SQLAlchemy code for my BookSchema and I want to find a specific title instead of an ID: 现在,这是我的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])

When I run this query, everything is fine and returns 3 book titles: 当我运行此查询时,一切都很好,并返回3个书名:

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

However, once I try to match a specific title, it stops working. 但是,一旦我尝试匹配特定的标题,它将停止工作。 For example: 例如:

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

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

I must be making a small error that I'm not seeing, but I can't figure it out. 我必须犯一个我没有看到的小错误,但我无法弄清楚。 I've spent hours trying to figure this out. 我花了几个小时试图弄清楚这一点。

Question: How can I match the title and have it return the object? 问题:如何匹配标题并使它返回对象? What am I doing wrong? 我究竟做错了什么?

Figured it out! 弄清楚了! See changes below. 请参阅下面的更改。

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

And my GraphQL query looks like this: 我的GraphQL查询看起来像这样:

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

Hope this helps someone in the future! 希望这对以后的人有所帮助!

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

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