Google App Engine NDB custom key id

…衆ロ難τιáo~ 提交于 2019-11-30 01:08:41

问题


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


回答1:


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.




回答2:


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.




回答3:


You can also supply integer ID (not necessarily a string) for your model entity.

class User(ndb.Model):
...

user = User(id=1234567890, ...)
user.put()


来源:https://stackoverflow.com/questions/13058327/google-app-engine-ndb-custom-key-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!