Google应用引擎:使用python返回实体ID的查询

时间:2021-03-05 23:14:23

how do I return the entity ID using python in GAE?

如何在GAE中使用python返回实体ID?

Assuming I have following

假设我有以下

class Names(db.Model):
   name = db.StringProperty()

2 个解决方案

#1


13  

You retrieve the entity, e.g. with a query, then you call .key().id() on that entity (will be None if the entity has no numeric id; see here for other info you can retrieve from a Key object).

您检索实体,例如使用查询,然后在该实体上调用.key()。id()(如果实体没有数字ID,则为None;有关可从Key对象检索的其他信息,请参阅此处)。

#2


5  

The question has long been answered.
(I am adding some full examples hopefully while not stepping on any toes...)

问题早已得到解答。 (我希望在不踩任何脚趾的情况下添加一些完整的例子...)

Getting an entity using a query; just getting the keys is faster and uses less CPU than retrieving the full entity:

使用查询获取实体;只需获取密钥比检索完整实体更快并且使用更少的CPU:

query = Names.all(keys_only=True)
names = query.get() # this is a shorter equivalent to `query.fetch(limit=1)`
names.id()

From a template:

从模板:

{{ names.id }}

GQL alternative, as suggested in a comment:

GQL替代方案,如评论中所示:

from google.appengine.ext import db

query = db.GqlQuery("SELECT __key__ FROM Names")
names = query.get()
names.id()

#1


13  

You retrieve the entity, e.g. with a query, then you call .key().id() on that entity (will be None if the entity has no numeric id; see here for other info you can retrieve from a Key object).

您检索实体,例如使用查询,然后在该实体上调用.key()。id()(如果实体没有数字ID,则为None;有关可从Key对象检索的其他信息,请参阅此处)。

#2


5  

The question has long been answered.
(I am adding some full examples hopefully while not stepping on any toes...)

问题早已得到解答。 (我希望在不踩任何脚趾的情况下添加一些完整的例子...)

Getting an entity using a query; just getting the keys is faster and uses less CPU than retrieving the full entity:

使用查询获取实体;只需获取密钥比检索完整实体更快并且使用更少的CPU:

query = Names.all(keys_only=True)
names = query.get() # this is a shorter equivalent to `query.fetch(limit=1)`
names.id()

From a template:

从模板:

{{ names.id }}

GQL alternative, as suggested in a comment:

GQL替代方案,如评论中所示:

from google.appengine.ext import db

query = db.GqlQuery("SELECT __key__ FROM Names")
names = query.get()
names.id()