Typhoon- Typhoon- - 3 months ago 22
Python Question

How to get a single value from gae ndb query?

I'm using Google App Engine with ndb backend and I want to get a single value ex:

int
from the ndb entity, after any query I get the whole entity with a projection, in my case I have a Transactions entity and I want to sum the amount properties.

What I'm using now is list comprehension on the query result like:

query = ndb.gql("select amount from Transactions").fetch()
result = sum([x.amount for x in query])


Is there any way to make ndb query returns a list of amounts only, so, I can sum the query result directly like:

query = ndb.gql("select amount from Transactions").fetch()
result = sum(query)


Thanks in advance

Answer

There is no direct way to get list of values from projection fetch (I suppose you are looking for ndb analog of django orm Transactions.query().all().values()), you may do as follows:

result = sum([x.amount for x in Transactions.query().fetch(
    projection=[Transactions.amount,])])

https://cloud.google.com/appengine/docs/python/ndb/projectionqueries