Google App Engine NDB custom key id

andrei picture andrei · Oct 24, 2012 · Viewed 9k times · Source

When I create an object with ndb's method put it creates the key automatically of the type Key(kind, id) where id is a number. All over the documentation it shows that you can use a string for the key's id but I couldn't find out how to do this automatically when an object is created.

I have a User model and I was thinking to use the user's username (since its unique) as the key's id for faster retrieval. Is that even a good idea? Would I have any problems with the username since it's user submited (i'm validating the input)?

Answer

bossylobster picture bossylobster · Oct 24, 2012
class UserModel(ndb.Model):
  ...

user_model_entity = UserModel(id='some_string', ...)

If these IDs are subject to change, this may be a bad idea. If it's your own system and you can react to potential changes, it is a fine idea, but you need make sure the IDs will be unique and relatively stable before deciding to use them.