Google App Engine NDB 自定义密钥 ID [英] Google App Engine NDB custom key id
问题描述
当我使用 ndb 的方法 put 创建一个对象时,它会自动创建 Key(kind, id) 类型的键,其中 id 是一个数字.在整个文档中,它表明您可以使用字符串作为密钥的 id,但我无法找到在创建对象时如何自动执行此操作.
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.
我有一个 User 模型,我想使用用户的用户名(因为它是唯一的)作为密钥的 id 以加快检索速度.这甚至是个好主意吗?因为用户名是用户提交的(我正在验证输入),所以我对用户名有什么问题吗?
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)?
推荐答案
class UserModel(ndb.Model):
...
user_model_entity = UserModel(id='some_string', ...)
如果这些 ID 可能会发生变化,这可能是个坏主意.如果它是您自己的系统并且您可以对潜在的变化做出反应,这是一个好主意,但在决定使用它们之前,您需要确保 ID 是唯一的且相对稳定.
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.
这篇关于Google App Engine NDB 自定义密钥 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!