如何在石墨烯烧瓶中制作多个查询过滤器?

时间:2018-01-29 11:07:24

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

我是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 个答案:

答案 0 :(得分:1)

老实说,鉴于已经定义了UserPost之间的关系,我会创建一个解析器,以便将这些组合结果一次性传递给两个参数:

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