views:

45

answers:

1

Hi am going through the docs of GAE and needed a small clarification. If I have my db model something like this:-

class Phone(Model):
  phone_name = db.StringProperty()

r = Phone(Nokia, key_name='first')
r.put()

Now if I have to retrieve this entity but I dont know the key, can I construct the key like this:

k=db.Key('Phone','first')

and once the key is constructed, can the entity be retrieved like this:-

r=db.get(k)
+1  A: 

You're close. The only major difference is that you have to pass the actual class instead of a string representing the class name, and that you have to use the Key.from_path() factory method rather than the default constructor:

class Phone(Model):
  phone_name = db.StringProperty()

r = Phone(phone_name='Nokia', key_name='first')
r.put()

k = db.Key.from_path('Phone', 'first')

r = db.get(k)

On the whole, however, I have found that relying on auto-generated IDs is usually a better solution than specifying your own key names. Is there a particular reason you're doing the latter?

Max Shawabkeh
Thanks a lot!... I am just learning
Alice
I don't think auto-generated IDs are better, they just have a different use case. If you have a predictable, fixed, unique identifier for an entity before it's stored, key names are a perfectly good solution.
Drew Sears
I agree that each has their use (hence "usually"). It's just that in most cases you'd be duplicating the effort of generating unique IDs, especially since in the end, it's much more convenient to pass encoded keys around rather than IDs or names.
Max Shawabkeh
Or you could also simply use r = Phone.get_by_key_name('first')
Franck
Thanks Frank, that was cool!
Alice
This is wrong: The kind argument to from_path is the string kind name, not the Phone class. Also, the Phone() constructor is wrong - it takes no positional arguments, so the first parameter should be 'phone_name="Nokia"'.
Nick Johnson