views:

164

answers:

3

I am working with google app engine and python.
I have a model with Items.
Immediately after I insert an item with item.put()
I want to get it's key and redirect to a page using this key

something like,

redirectUrl = "/view/key/%s/" % item.key
self.redirect(redirectUrl)
+1  A: 

After you did you put() you can run

item.key().id()

Getting the id() is slightly safer than just using key() directly, since you'd be indirectly calling __str__(), which may not happen in a non strincg context.

The other options is to call id_or_name(), but then you probably would already know what the name is in that case.

Scott Kirkwood
A: 

Thanks for the initiative Scott Kirkwood. I was actually missing the ()

redirectUrl = "/view/key/%s/" % item.key()
self.redirect(redirectUrl)

Good to know that in google datastore you don't need to use anything like Scope_identity, but you can just get the item.key() just after item.put()..

Stavros
+1  A: 

Also, item.put() returns the key as the result, so it's hardly ever necessary to fetch that key immediately again -- just change your sequence, e.g

  item.put()
  redirectUrl = "/view/key/%s/" % item.key()

into

  k = item.put()
  redirectUrl = "/view/key/%s/" % k
Alex Martelli
cool! thanks ;-)
Stavros