【问题标题】:How do I sum a list of attributes from a Google Datastore query result?如何汇总来自 Google Datastore 查询结果的属性列表?
【发布时间】:2022-01-22 07:25:35
【问题描述】:

寻找一种使用 ndb 查询对属性列表求和的有效方法。目前我只是获取结果并在它们上运行一个 for 循环。

class Player(ndb.Model):
    score = ndb.IntegerProperty()

score_of_group = 0
all_players = Player.query().filter("various filters").fetch()
for player in all_players:
    score_of_group += player.score

【问题讨论】:

    标签: python-2.7 google-app-engine google-cloud-datastore


    【解决方案1】:

    如果这是您拥有的模型(单个模型)并且您的“各种过滤器”只是过滤该单个模型的不同方式,我不相信您可以直接在查询中求和。

    对于 Python 代码本身,您可以使用内置的 sum 函数,因此您的代码可能类似于

        all_players = Player.query().filter("various filters").fetch()
        score_of_group = sum([x.score for x in all_players])
    

    如果您碰巧有至少 2 个模型,并且您正在根据另一个模型中的值从另一个模型中获取记录(例如,您有一个人员列表,并且您需要从另一个表中检索他们的所有比赛/得分),那么您应该查看@ndb.tasklet 以加快数据检索/使其更高效,但您仍然需要自己总结

    【讨论】:

    • 我就是这么想的。这种迭代和求和是不可避免的。再次感谢。
    猜你喜欢
    • 2021-02-21
    • 2021-12-08
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多