bobobobo
bobobobo

Reputation: 67224

GQL get ID field

On google appengine, you can retrieve the hash key value by doing a query like

select __key__ from furniture

But appengine datastore maintains a nicely autoincremented field ID for each kind.

How can I access it from a query?

select ID from furniture

Doesn't work

Upvotes: 3

Views: 3761

Answers (3)

sadaf2605
sadaf2605

Reputation: 7540

I am not sure if it was there back then when you have asked this question, but now it is pretty easy to retrieve entity by id.

YourModel.get_by_id (int(ids))

You can read more about it here in the documentation: https://developers.google.com/appengine/docs/python/datastore/modelclass#Model_get_by_id

Upvotes: 0

bertamarie
bertamarie

Reputation: 51

you could also try

entity.key().id()

Upvotes: 5

Alex Martelli
Alex Martelli

Reputation: 881477

I believe that a Gcl query cannot incorporate calls to accessor methods or attribute extraction (much in the same vein as the fact it can only do "SELECT * FROM" to fetch whole entities or "SELECT __key__ FROM" to fetch keys only -- it cannot pick and choose fields as in [hypothetical!-)] "SELECT this, that FROM").

So, you need to fetch the keys, then call each key's .id() accessor (if you want None for keys that don't have an ID but rather a name; use .id_or_name() if you'd rather get the name, if available, and None only as a last resort). E.g., to get non-None IDs only:

thekeys = db.GqlQuery('SELECT __key__ FROM Whatever').fetch(1000)
theids = [k.id() for k in thekeys if k.id() is not None]

Upvotes: 4

Related Questions