Building GraphQL API with Python & Django Part #7: Filtering and Pagination
In this post we will add the filtering and pagination functionality to our application that allow to filter Human character
In this post, we are going to add search functionality to the application. We will be filtering the Human character by name and its home planet. We will also add the pagination functionality.
Filtering Human Characters
You already can list all humans, but another feature of we want to add is to search them, by the name and homeplanet. In GraphQL, this concept is the same as mutations: you pass an argument to the links field, used by the resolver to filter the results.
We will update the humans Query to accept the one argument
class Query(graphene.ObjectType):
humans = graphene.List(
HumanType,
#1
search=graphene.String(),
)
def resolve_humans(self, info, search, first, skip):
humans = resolver_humans()
#2
if search:
filter = (
Q(name__icontains=search) |
Q(home_planet__icontains=search)
)
humans = humans.filter(filter)
return humans
Let's walk through the comments to understand the code:
We have defined the search as an argument into the humans Query
If search arguments are there we will filter the results by the search query
Run the below query in GraphiQL interface to filter the human character
{
humans (search: "Luke") {
id
name
height
mass
birthYear
homePlanet
}
}
You can change the search query to see how the result changes with the query.
Imagine that your Application has thousands of created humans character – that would be awesome for you – but the clients making the request wouldn’t be happy. Retrieving too much data on a single request is unpractical and may even break your app. Pagination exists to solve this problem, allowing the client to specify how many items it wants.
The simple way defined in the GraphQL pagination documentation is to slice the results using two parameters: first, which returns the first n items and skip, which skips the first n items.
class Query(graphene.ObjectType):
humans = graphene.List(
HumanType,
search=graphene.String(),
first=graphene.Int(),
skip=graphene.Int(),
)
def resolve_humans(self, info, search, first, skip):
humans = resolver_humans()
if search:
filter = (
Q(name__icontains=search) |
Q(home_planet__icontains=search)
)
humans = humans.filter(filter)
if skip:
humans = humans[skip:]
if first:
humans = humans[:first]
return humans
Run the below query in GraphiQL interface to filter the human character with pagination and skip query specified
{
humans (search: "Tatoonie", first:2, skip:0) {
id
name
height
mass
birthYear
homePlanet
}
}
You can change the search query to see how the result changes with the query.
Congratulations, you’ve reached the end of the Python GraphQL tutorial! Here, you’ve learned about the most used Python library for developing a GraphQL server – Graphene – together with Django and Graphene-Django.