I'm using graphene with sqlalchemy and I have an output object that contains a computed field. The field is computed according to some input (query) parameter and more or less look like this (to simplify, lets consider I'm computing f(x)=ax+b where a and b are both columns in my
Thing
table):
import models
class Thing(SQLAlchemyObjectType):
class Meta:
model = models.Thing
interfaces = (relay.Node, )
f = graphene.Field(graphene.Float)
def resolve_f(self, info):
return self.a * info.context['x'] + self.b
In my query I have the following and I would like to sort fields according to the output of the function f
:
class Query(graphene.ObjectType):
best_points = graphene.List(lambda: Thing, x = graphene.Float())
def resolve_best_points(self, info, x):
query = Thing.get_query(info)
return query.all()
At first I've tried sorting within resolve_best_points
using something like query.order_by("f").all()
but in vain since graphene seems to add this field outside the resolver (ie., query.all()
only contains a
and b
but not f(a, b)
).
Is there a way to achieve this in a clean way? Adding some option in Thing
? Or maybe obtaining the output values within the resolver and then sorting? Or something a bit uglier like adding a middleware to sort outputs from resolve_best_points
?
What is possible, what are the pros/cons of possible solutions to this?
Note that this is somewhat related to this question: Sqlalchemy order by calculated column, but this is also quite different because here I don't want a calculation based on database fields only (current solutions do not work when there are variables involved, like info.context['x']
in this toy example).