I'm trying to return distinct values from a GraphQL query.
from graphene_sqlalchemy import SQLAlchemyConnectionField
import graphene
from database.model import MyModel
class Query(graphene.ObjectType):
"""Query objects for GraphQL API."""
node = graphene.relay.Node.Field()
distinct_values = graphene.List(graphene.String, search=graphene.String())
def resolve_distinct_values(self, info, search=None, **kwargs):
return MyModel.field.distinct()
schema = graphene.Schema(query=Query)
The response I receive from my distinctValues query is:
{
"message": "User Error: expected iterable, but did not find one for field Query.distinctValues."
}
There's got to be something simple I'm overlooking here. What is distinct() intended to do?
SQLAlchemy's
distinct
method is used to add aDISTINCT
clause to your query.DISTINCT
will remove all duplicate rows.If you're using PostgreSQL, you can also use the optional parameter,
distinct(*expr)
, to render aDISTINCT ON (<expressions>)
clause. This will keep only the "first row" of each set of rows where the given expressions (*expr
) evaluate to equal. You'll need to use SQLAlchemy'sorder_by
method to ensure that the desired row appears first.SQLAlchemy's Query.distinct(*expr) method.
PostgreSQL's DISTINCT Clause.
This example shows a game in which players can travel to different islands, a visit is recorded each time a player arrives at an island. We can use the
lastVisit
field to show the most recent player to have visited each island.This query:
Would produce this result: