如何在石墨烯烧瓶中进行多个查询过滤器?
Posted
技术标签:
【中文标题】如何在石墨烯烧瓶中进行多个查询过滤器?【英文标题】:How to make multiple queries filters in graphene flask? 【发布时间】:2018-07-08 01:30:44 【问题描述】:我是 GraphQL 的新手,我正在尝试进行这样的查询
user(username: "Jon")
name
last_lame
username
posts(in_draft : true)
title
text
in_draft
update_at
我想过滤用户在草稿中的帖子列表
我可以进行查询的唯一方法是通过模型的关系,但无法过滤草稿中的帖子。 一对多
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String)
last_lame = Column(String)
username = Column(String)
class Post(Base):
__tablename__ = 'post'
id = Column(Integer, primary_key=True)
title = Column(String)
text = Column(String)
in_draft = Column(Boolean)
post_id = Column(Integer, ForeignKey('user.id'))
posts = relationship("User", backref='posts')
有了这种关系,我用“backref = 'posts'”显示帖子节点
我的对象:
class User(SQLAlchemyObjectType):
"""User Object."""
class Meta:
model = UserModel
interfaces = (relay.Node, )
class Post(SQLAlchemyObjectType):
"""Post Object."""
class Meta:
model = PostModel
# interfaces = (relay.Node, )
查询:
class Query(graphene.ObjectType):
user = graphene.Field(lambda: User, username=graphene.String())
def resolve_user(self, info, username):
query = User.get_query(info)
return query.filter(UserModel.username == username).first()
我想让帖子的查询属于用户
posts = graphene.List(lambda: Post, in_draft=graphene.Boolean())
def resolve_posts(self, info, in_draft):
query = Post.get_query(info)
return query.filter(PostModel.in_draft == in_draft).all()
schema = graphene.Schema(
query=Query,
types=[User, Post])
有什么想法或建议吗?
【问题讨论】:
【参考方案1】:老实说,鉴于 User
和 Post
之间的关系已经定义,我将创建一个解析器来让这些组合结果同时传递两个参数,如下所示:
class Query(graphene.ObjectType):
filter_user_posts = graphene.List(
lambda: User,
username=graphene.String,
in_draft=graphene.Boolean,
)
def resolve_filter_user_posts(
self, info, username, in_draft
):
query = User.get_query(info=info)
query = query.join(User.posts)
query = query.filter(User.username == username)
query = query.filter(Post.in_draft == in_draft)
objs = query.all()
return objs
然后您可以像这样简单地查询:
filterUserPosts(username: "Jon", in_draft: true)
name
last_lame
username
posts
title
text
in_draft
update_at
【讨论】:
对我有用,但需要进行一点更正或澄清。在 filter_user_posts 。该行应该是 username=graphene.String()。字符串是一个类以上是关于如何在石墨烯烧瓶中进行多个查询过滤器?的主要内容,如果未能解决你的问题,请参考以下文章