Google 应用引擎 如何计算日期存储中的 SUM?

发布于 2024-08-29 22:46:31 字数 168 浏览 4 评论 0原文

我想知道,如何获得从数据存储(python)中获得的评级实体的总和?

我应该:

ratingsum = 0
for rating in ratings:
    ratingsum + rating

print ratingsum

Im wondering, how can i get a SUM of a rating entity i get from the datastore (python)?

should i:

ratingsum = 0
for rating in ratings:
    ratingsum + rating

print ratingsum

?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

初与友歌 2024-09-05 22:46:31

是的,差不多就是这样。检索您想要求和的所有实体,并在您的应用程序中对它们求和。 GQL 中没有 SUM

如果您想要完成的任务是找到某个实体的平均评级,那么有更好的方法。

class RateableThing(db.Model):
    num_ratings = db.IntegerProperty()
    avg_rating = db.FloatProperty()

找到事物的平均评级是一个简单的查找,添加一个新的评级只是:

thing.avg_ratings = ((thing.avg_ratings * thing.num_ratings) + new_rating) / thing.num_ratings + 1
thing.num_ratings += 1
thing.put()

App Engine数据存储区的流行习惯是在写入时做尽可能多的工作,在读取时尽可能少做工作,因为会发生读取更频繁。

Yep, that's pretty much it. Retrieve all the entities you want to sum, and sum them in your app. There is no SUM in GQL.

If what you're trying to accomplish is to find the average rating for an entity, there's a better way.

class RateableThing(db.Model):
    num_ratings = db.IntegerProperty()
    avg_rating = db.FloatProperty()

Finding the thing's average rating is a simple lookup, and adding a new rating is just:

thing.avg_ratings = ((thing.avg_ratings * thing.num_ratings) + new_rating) / thing.num_ratings + 1
thing.num_ratings += 1
thing.put()

The prevailing idiom of the App Engine datastore is to do as much work as you can on write, and as little as possible on read, since reads will happen much more often.

狼性发作 2024-09-05 22:46:31

我无法回答您问题的 Google App Engine 部分,但您的代码(如果您将 + 更改为 +=)相当于:

ratingsum = sum(ratings)

我很漂亮确保您可以在任何包含类似数字对象的序列或可迭代对象上使用 sum()

I can't answer the Google App Engine part of your question, but your code (if you change the + to a +=) is equivalent to:

ratingsum = sum(ratings)

I'm pretty sure you can use sum() on any sequence or iterable containing number-like objects.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文