Get NDB query length - using Python on Google App Engine
Asked Answered
W

2

5

What is a good way to get the number of query result when using NDB on google app engine?

Attempted this:

query = NDB_Model.query(NDB_Model.some_property == some_value)
if len(query) > 0:    # <-- this throws and exception
    entity = query[0]

I apologize that this is probably a very simple question, but it was not clear to me from the docs.

Wineshop answered 31/8, 2012 at 18:18 Comment(0)
L
12

It seems like you just want to get the first entity from your query. That's what query.get() is for.

query = NDB_Model.query(NDB_Model.some_property == some_value)

entity = query.get()
if entity is not None:
    # Do stuff

From the docs:

Returns the first query result, if any (otherwise None). This is similar to calling q.fetch(1) and returning the first item of the list of results.

In a more general form, there's query.fetch(n) where n is the maximum number of entities to fetch. It returns a list, so you could easily check len() on that.

Longley answered 31/8, 2012 at 18:26 Comment(4)
Thanks so much for your response, I felt stupid when I found the part about using "fetch()" in the docs shortly after I posted this question. But I'm still glad I asked because would have done "query.fetch(1)[0]" instead of the much better "query.get()"Wineshop
@ChrisDutrow: No problem! When you do use q.fetch(n), be sure to check the length, because fetch returns up to n entities, but it can return less. The n is just a limit.Longley
@Longley What is a good way to get the number of query result (just the count only) when using NDB ?.Mattox
@Nijo: query.count(limit). It's right in the docs.Longley
S
3

To get the result count of a ndb query you can simply use count():

query = NDB_Model.query(NDB_Model.some_property == some_value)
if query.count() > 0:
    entity = query[0]
Socinus answered 20/4, 2014 at 18:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.