Peter
Peter

Reputation: 53

Google app engine: query that return entity ID using python

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

Assuming I have following

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

Upvotes: 5

Views: 3622

Answers (2)

mechanical_meat
mechanical_meat

Reputation: 169524

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:

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:

from google.appengine.ext import db

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

Upvotes: 5

Alex Martelli
Alex Martelli

Reputation: 882751

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).

Upvotes: 13

Related Questions