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?
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.
Assuming you really meant name vs. id, it’s a matter of whichever is more convenient. Any performance difference is going to be microscopic.