Reputation: 625
I'm a relative newcomer to GraphQL, I'm trying to make a query like this
{
user(username: "Jon") {
name
last_lame
username
posts(in_draft : true) {
title
text
in_draft
update_at
}
}
}
I want to filter the list of posts that the user has in draft
The only way I can do the query is through the relationship of the models, but without being able to filter in the posts in draft. One to many
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')
With this relationship, I show the posts node with "backref = 'posts'"
My objects:
class User(SQLAlchemyObjectType):
"""User Object."""
class Meta:
model = UserModel
interfaces = (relay.Node, )
class Post(SQLAlchemyObjectType):
"""Post Object."""
class Meta:
model = PostModel
# interfaces = (relay.Node, )
Query:
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()
I want to make the query of the posts belong to the user
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])
Any idea or suggestion?
Upvotes: 3
Views: 4803
Reputation: 1314
Honestly, given that the relationship between User
and Post
is already defined I would create a single resolver to get those combined results passing the two arguments at once like this:
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
which you can then simply query like this:
{
filterUserPosts(username: "Jon", in_draft: true) {
name
last_lame
username
posts{
title
text
in_draft
update_at
}
}
}
Upvotes: 5