获取NDB查询长度 - 在Google App Engine上使用Python

时间:2021-09-03 03:52:19

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

在谷歌应用引擎上使用NDB时,获取查询结果数量的好方法是什么?

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.

我很抱歉这可能是一个非常简单的问题,但我从文档中不清楚。

2 个解决方案

#1


12  

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

您似乎只想从查询中获取第一个实体。这就是query.get()的用途。

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.

返回第一个查询结果(如果有)(否则为None)。这类似于调用q.fetch(1)并返回结果列表的第一项。

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.

在更一般的形式中,有query.fetch(n),其中n是要获取的最大实体数。它返回一个列表,因此您可以轻松检查len()。

#2


3  

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

要获取ndb查询的结果计数,您只需使用count():

query = NDB_Model.query(NDB_Model.some_property == some_value)
if query.count() > 0:
    entity = query[0]

#1


12  

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

您似乎只想从查询中获取第一个实体。这就是query.get()的用途。

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.

返回第一个查询结果(如果有)(否则为None)。这类似于调用q.fetch(1)并返回结果列表的第一项。

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.

在更一般的形式中,有query.fetch(n),其中n是要获取的最大实体数。它返回一个列表,因此您可以轻松检查len()。

#2


3  

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

要获取ndb查询的结果计数,您只需使用count():

query = NDB_Model.query(NDB_Model.some_property == some_value)
if query.count() > 0:
    entity = query[0]