【问题标题】:Why ValueError when deleting a KeyProperty type to one-to-many relationship. How to fix it?为什么将 KeyProperty 类型删除为一对多关系时出现 ValueError。如何解决?
【发布时间】:2026-01-27 08:35:01
【问题描述】:

我有一个一对多的关系 NDB 实体模型 b/w 帖子和评论模型。从数据库中删除评论实体后,我试图从 cmets 列表中删除评论。以下是我删除评论的代码:

idx = post.comments.index(ndb.Key('Comment',comment_id))
post.comments.pop(pos) # Remove comment from comments list

我收到如下错误:

ValueError: Key('Comment', '6614661952700416') 不在列表中

但在 Datastore Viewer 上我可以看到评论:

[datastore_types.Key.from_path(u'Comment', 6614661952700416L, _app=u'dev~testData2')]

帖子模型:

class Post(ndb.Model):
    title = ndb.StringProperty(required=True)
    body = ndb.TextProperty(required=True)
    created = ndb.DateTimeProperty(auto_now_add=True)
    updated = ndb.DateTimeProperty(auto_now=True)

    author_id = ndb.KeyProperty(kind=User)

    comments = ndb.KeyProperty(kind=Comment, repeated=True)

similar question 上似乎可以正常工作。

【问题讨论】:

  • 尝试将 ID 转换为 int idx = post.comments.index(ndb.Key('Comment', int(comment_id)))。错误消息表明它被解释为字符串。此外,在查看器中显示的可选_app 也很不寻常。评论是如何创建的? 'dev~testData2' 是否与您的应用匹配?
  • 解决了这个问题。谢谢

标签: python-2.7 google-app-engine app-engine-ndb webapp2


【解决方案1】:

将评论转换为答案。

错误消息表明 comment_id 被解释为字符串,而不是 long/int(强调我的):

ValueError: Key('Comment', '6614661952700416') 不在列表中

虽然数据存储条目对应一个长密钥 ID:

[datastore_types.Key.from_path(u'Comment', 6614661952700416L, _app=u'dev~testData2')]

所以只需将comment_id 显式转换为一个数字:

idx = post.comments.index(ndb.Key('Comment', int(comment_id)))

【讨论】: