You need to enable JavaScript to run this app. App Engine Datastore ndb模型如何指定自定义实体ID
优惠活动
大模型
产品
解决方案
定价
更多

App Engine Datastore ndb模型如何指定自定义实体ID

你之前的两次写法的问题分别是:

  1. 用KeyProperty定义id:该字段要求传入的是NDB Key对象,字符串类型的单词自然无法通过校验
  2. 用StringProperty定义id:该字段属于普通业务属性,和Datastore内置的实体ID完全独立,因此系统会自动生成默认的数字ID,不会复用你自定义的id字段值

正确实现方案

  1. 调整模型定义,删除多余的自定义id字段,实体ID属于NDB内置属性,无需显式声明:
class Word(ndb.Model):
    definition = ndb.StringProperty(required=True)
  1. 新增实体时,在实例化模型类阶段直接传入id参数指定单词作为自定义ID:
word = Word(id="love")
word.definition = "a profoundly tender, passionate affection for another person. "
word.put()
  1. 按单词查询释义可直接调用内置的get_by_id方法,无需额外建立索引:
# 查询单词love的释义
word_entry = Word.get_by_id("love")
if word_entry:
    print(word_entry.definition)

内容的提问来源于stack exchange,提问作者salyela

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 13:24:10