Python – Selecting based on __key__ (a unique identifier) in google appengine

google-app-enginepython

Again i have


""" A site message """
class Message( db.Model ) :
  # from/to/ a few other fields
  subject = db.StringProperty()
  body = db.Text()

  sent = db.DateTimeProperty( auto_now_add=True )

Now I'm trying to pick out a Message by its KEY. I saved off the key earlier and planted it in an HTML form. The result is a clickable link that looks something like

<a href="/readmessage?key=aght52oobW1hZHIOCxIHTWVzc2FnZRiyAQw">click to open</a>

So then I run this GQL query:

gql = """select * from Message where __key__='aght52oobW1hZHIOCxIHTWVzc2FnZRiyAQw'"""

But its not working because

BadFilterError: BadFilterError: invalid filter: __key__ filter value must be a Key; received aght52oobW1hZHIOCxIHTWVzc2FnZRiyAQw (a str).

I'm totally missing something here, and that is how do you put an object into a GQL query string.. and not have Gql parser complain of that it is a string?

Best Answer

Don't bother with GQL for key-based retrieval -- make a key object from the string:

k = db.Key('aght52oobW1hZHIOCxIHTWVzc2FnZRiyAQw')

and just db.get(k). If you insist on GQL, btw, that k -- a suitably constructed instance of db.Key, NOT a string object!-) -- is also what you need to substitute into the GQL query (by :1 or whatrever).