Google App Engine NDB custom key id

2019-02-11 19:02发布

问题:

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