views:

155

answers:

2

hi

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

Assuming I have following

class Names(db.Model):
   name = db.StringProperty()
+4  A: 

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

Alex Martelli
You can also SELECT ____key____ FROM ... using GQL, which is a quick way to get the key without the overhead of loading the full entity.
Dave W. Smith
Could you mind write the complete coding as I really new to datastore
Peter
Thanks, I figured it out now
Peter
+1 for being much faster than me.
Adam Bernier
+2  A: 

The question has long been answered by the Martelli-bot ;-)
I wanted to add 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()
Adam Bernier