bobobobo
bobobobo

Reputation: 67254

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

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?

Upvotes: 1

Views: 2179

Answers (2)

bossylobster
bossylobster

Reputation: 10163

You can also construct a query by hand by constructing "an entity key literal, with...a complete path of kinds and key names/IDs".

SELECT * FROM Message WHERE __key__ = KEY('Message', 'message_key')

This is even more helpful if you are using the Datastore Viewer/Explorer and can't use Python syntax.

Upvotes: 1

Alex Martelli
Alex Martelli

Reputation: 881805

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

Upvotes: 6

Related Questions