Get NDB query length - using Python on Google App Engine

廉价感情. 提交于 2019-12-10 15:08:26

问题


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.


回答1:


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.




回答2:


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]


来源:https://stackoverflow.com/questions/12220653/get-ndb-query-length-using-python-on-google-app-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!