使用 GraphQL 显示统计信息



我对 GraphQL 和 Graphene 相当陌生,我找不到任何可以帮助我解决问题的东西,所以现在在这里问。

基本上,我想要显示的是仅给定列表的活动、非活动和暂停用户的数量。我在进行查询时想到的是这样的:

query{
viewer{
statistics(listId:5) {
active
inactive
suspended
}
}
}

并接收如下输出:

{
"data": {
"viewer": {
"statistics": {
"active": 11,
"inactive": 12,
"suspended": 13
}
}
}

这是我目前拥有的(我正在使用 Python(:

class Statistic(SQLAlchemyObjectType):
class Meta:
model = EmployeeModel
interfaces = (relay.Node, )
active= graphene.Int()
inactive= graphene.Int()
suspended= graphene.Int()
@staticmethod
def resolve_active(self, args, context, info):
return 11
@staticmethod
def resolve_inactive(self, args, context, info):
return 12
@staticmethod
def resolve_suspended(self, args, context, info):
return 13
class Viewer(graphene.ObjectType):
node = relay.Node.Field()
statistics = graphene.List(Statistic, list_id=graphene.Int())
def resolve_active_employees(self, args, context, info):
list_id = args.get('list_id')
if (employeelist is None):
raise GraphQLError("Missing argument: list_id (Employee List ID)")
return db_session.query(EmployeeModel) 
.join(EmployeeListModel,
EmployeeModel.employeelist_id == EmployeeListModel.id ) 
.filter(EmployeeModel.terminated == 0) 
.filter(EmployeeListModel.id == employeelist)

所以肯定我没有得到我想要的,相反,我收到了活跃(或非终止(用户的所有记录。我不知道该用什么,所以这就是我现在得到的和卡住的。

有人可以指出我如何实现目标输出的正确方向(不是真的希望得到硬编码的答案,如果可能的话,最好结果应该来自数据库查询(?

我正在使用:

graphene==1.4.1
graphene-sqlalchemy==1.1.1
graphql-core==1.1
graphql-relay==0.4.5

在工作中,我们也开始使用石墨烯进行分析。 虽然我们使用graphene_django而我还没有使用SQLAlchemy,但我希望我能为您提供一些如何解决问题的想法:

我不确定我是否正确理解了您的代码,但您可能想要类似的东西

class Viewer(graphene.ObjectType):
node = relay.Node.Field()
statistics = graphene.List(Statistic, list_id=graphene.Int())
# Use `resolve_statistics'  to define how you get the data for the 
# statistics list
def resolve_statistics(self, args, context, info):
list_id = args.get('list_id')
# Some query which filters your model for the given ID and annotates or
# aggregates the stats
return <you query which filters for list id and annotates stats>

然后,您的查询可以返回一个字典,例如{'active': 11, 'inactive': 12, 'suspended':13}.

如果选择这种方式,则需要调整Statistics对象类型以从字典中提取字段值:

class Statistic(SQLAlchemyObjectType):
class Meta:
model = EmployeeModel
interfaces = (relay.Node, )
active= graphene.Int()
inactive= graphene.Int()
suspended= graphene.Int()
def resolve_active(self, args, context, info):
return self.get('active')
def resolve_inactive(self, args, context, info):
return self.get('inactive')
def resolve_suspended(self, args, context, info):
return self.get('suspended')

我不太确定这是否是你想要的,但也许它会给你一些想法。 例如,我们要做的是使用django_filter包,您可以在其中更轻松地进行过滤。不幸的是,我不知道你是否可以在SQLAlchemy中做类似的事情。

我也不确定为什么您将EmployeeModel用作Statistics对象类型的元模型。如果您只想拥有一个包含activeinactivesupscended员工的统计字段,您也可以创建一个简单的ObjectType而无需基本模型 - 但也许我只是理解错了。

最新更新