views:

430

answers:

1

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

+3  A: 

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]
Alex Martelli
Absolutely correct, except that the condition should probably be "if k.has_id()" - or omit it and use "k.id_or_name()".
Nick Johnson
@Nick, thanks! `has_id` is NOT documented at http://code.google.com/appengine/docs/python/datastore/keyclass.html so I'm reluctant to use it or advise others to use it -- if that's a docs bug, I'll be glad to open it in the tracker and/or help fit it in 20% time, of course;-).
Alex Martelli