Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gae Model get_by_id() vs get_by_key_name()

I am wondering about fetching records using Model.get_by_key_name() vs Model.get_by_id()

For example, let's say I am returning some JSON that will be used to display a table of records, and for each record, there is a button to delete that record. Suppose I have model 'Foo' and model instance 'foo'.

I believe I can associate each button with the appropriate record using either:

str(foo.key())  #suppose it eval's to "axhYm92ZZXJvY2tyDgsSCENhnb3J5GBQM"

or

foo.key().id()  #suppose it eval's to "57"

One of these values will make its way into an HTML form, and user may click the button which makes the request to delete the record with this key/id.

The request would then result in either:

Foo.get_by_key_name("axhYm92ZZXJvY2tyDgsSCENhnb3J5GBQM").delete()

or

Foo.get_by_id(57).delete()

Now, being the indecision-riddled ADHD programmer that I am, I need to know ... which is the "right" way? They both seem to work, but are there circumstances that make one preferable to the other? Is there some advantage to using the 'key' way vs the 'id' way?

like image 360
thedudeabides Avatar asked Jun 05 '11 00:06

thedudeabides


2 Answers

You're confusing a Key name with the stringified Key. They're different. A key's name is something you give an entity via the reserved key_name property at construction time. If you don't, the system will generate an id. An entity key can have either a name or an id, but not both.

If you've intentionally stringified a Key, you reconstitute it by passing it back to the Key constructor.

stringifiedKey = str(key)
reconstitutedKey = db.Key(stringifiedKey)

Assuming you really meant name vs. id, it's a matter of whichever is more convenient. Any performance difference is going to be microscopic.

like image 88
Dave W. Smith Avatar answered Sep 23 '22 02:09

Dave W. Smith


What you are getting is a key string not a key_name. If you want to get a object from it's key string. Then you use Model.get(keystring) . Key_name is what you assign to a object which is supposed to be unique. If you think you could use any attribute which is unique you can make it as a key_name else go for the default generated id. Only thing you get in using a key_name is get_or_insert() which returns a entity if a entity with that key name exists else creates one and returns it.

like image 40
Abdul Kader Avatar answered Sep 25 '22 02:09

Abdul Kader