1

I have tried to delete an entity from the GAE datastore for hours now and it doesn't work as it should. I pretty much did the same thing as how to delete NDB entity using ID?, however I'm sure the problem is with the ancestor relationship.

This is the relevant piece of code:

try:
 ndb.Key('NewsBase', int(self.request.get('delid'))).delete()

When I print out the ndb.Key (self.request.out.write...) I get something like Key('NewsBase', 8008), which is the correct ID (checked in datastore). In the dashboard I also get the "Decoded entity key", which is

NewsBase: name=mynews > NewsBase: id=8001

I am a little confused on how to include the ancestor information but as far as I can tell from here Using Key in NDB to retrieve an entity I don't need it at all, or do I?

EDIT: How I create keys

def news_key(base_name='mynews'):
    return ndb.Key('NewsBase', base_name)

    t = NewsBase(parent=news_key('mynews'))
    t.user = user
    t.put()
4

2 回答 2

2

您需要完整的密钥,包括祖先(如果有的话)。这是因为子 ID 本身不一定是唯一的:只有完整路径是唯一的,因此您需要它来识别特定实体。

在你的情况下,你可能只是想要nb.Key('NewsBase', 'mynews', 'NewsBase', 8001).

(不过,我怀疑您首先在创建密钥时做了一些奇怪的事情:拥有与孩子的数字 ID 具有相同类型的名称密钥的祖先是不寻常的。)

于 2013-06-17T12:31:23.263 回答
1

尝试使用urlsafe密钥的版本而不是 ID:

将密钥输出为:

key.urlsafe()代替key.id()

并在您的请求处理程序中将其删除为:

ndb.Key(urlsafe=self.request.get('delkey')).delete()

密钥的urlsafe版本将包含所有必要的祖先信息。

另外,您的news_key功能是否知道其制作的关键存在?您不应该为不存在的实体存储具有父键的实体。

news_key可能应该更像是:

 def news_key(base_name='mynews'):
    return NewsBase.get_or_insert(id=base_name).key

仅供参考 - 删除父级并不会删除所有子级。此外,按照您在此处显示的方式,您的NewsBase实体的父级将是另一个NewsBase实体。

于 2013-06-17T13:58:38.483 回答