Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google App Engine NDB custom key id

Tags:

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)?

like image 870
andrei Avatar asked Oct 24 '12 21:10

andrei


2 Answers

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.

like image 157
bossylobster Avatar answered Oct 02 '22 12:10

bossylobster


You specify the id of the entity at the time of creation. When you define the model, you don't set an id attribute there. Thus, for example you have:

class User(ndb.Model):     # fields here 

When you create the model, you have:

user = User(id='username', ...) 

Since the username is unique and you validate your input, then you will not have any problems with this approach.

For more information about an ndb Model constructor, you can take a look at NDB Model Class - Constructor.

Hope this helps.

like image 33
Thanos Makris Avatar answered Oct 02 '22 12:10

Thanos Makris