Google App Engine NDB custom key id

别等时光非礼了梦想. 提交于 2019-11-30 17:05:26
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.

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.

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

class User(ndb.Model):
...

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