Home > Back-end >  How do I sum a list of attributes from a Google Datastore query result?
How do I sum a list of attributes from a Google Datastore query result?

Time:12-21

Looking for an efficient way to sum a list of attributes using ndb queries. Currently I just fetch the results and run a for loop over them.

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

CodePudding user response:

If that's the model (a single model) you have and your '''various filters' are just different ways to filter that single model, I don't believe you can sum directly in the queries.

For the Python code itself, you can use the inbuilt sum function and so your code could be something like

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

If you happen to have at least 2 models and you are fetching records from another model based on the value in another model (e.g. you have a list of people and you need to retrieve all their plays/scores from another table), then you should look at @ndb.tasklet to speed up the data retrieval/make it more efficient but you would still have to sum it yourself

  • Related