gpt4 book ai didi

python - 聚合 Graphite 烯/django 查询中的字段

转载 作者:行者123 更新时间:2023-12-04 15:29:45 27 4
gpt4 key购买 nike

我正在编写一个 Graphite 烯/django ORM 查询,我需要在我的所有查询结果对象上聚合特定字段的值并将其与查询一起返回。不太确定如何做到这一点,因为这涉及一些后期处理。如果有人可以提供一些指导,将不胜感激。

这是一些示例代码。 Django 模型类“市场”有一个整数字段“num_vendors”。 Graphite 烯包装器是围绕“市场”模型类的“MarketNode”:

模型类:

class Market(models.Model):
num_vendors = models.IntegerField(....)

Graphite 烯类:
class MarketNode(DjangoObjectType):
Meta:
model: Market

我希望查询返回“market_count”(有多个市场)和“vendor_count”(所有市场中所有“供应商”的总和)。所以查询看起来像:
allMarkets {
market_count
vendor_count
edges {
node {
...
...
num_vendors
...
}
}
}

对于market_count,我正在关注这个例子(这很好用):
https://github.com/graphql-python/graphene-django/wiki/Adding-counts-to-DjangoFilterConnectionField

对于 vendor_count(跨所有市场),我假设我需要在查询完成并解决后迭代结果并添加所有 num_vendors 字段。我怎样才能做到这一点?这一定是一个相当普遍的用例,所以我确信 Graphite 烯提供了一些钩子(Hook)来做到这一点。

最佳答案

您可以使用计数字段定义 MarketConnection。
就像是:


class MarketConnection(graphene.relay.Connection):
class Meta:
node = Market

market_count = graphene.Int(required=True)
vendor_count = graphene.Int(required=True)

def resolve_market_count(self, info, **kwargs):
return self.iterable.count() if isinstance(self.iterable, QuerySet) else len(self.iterable)

def resolve_vendor_count(self, info, **kwargs):
if isinstance(self.iterable, QuerySet):
return self.iterable.aggregate(Count("vendor"))
return sum([market.num_vendors for market in self.iterable])
并将 connection_class 添加到您的 MarketNode
class MarketNode(DjangoObjectType):
class Meta:
model: Market
connection_class: MarketConnection

关于python - 聚合 Graphite 烯/django 查询中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61468812/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com