1
votes

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()
2
Are you trying to create a structure where a NewsBase entity will be the parents to more NewsBase entities? Are you sure you did not mean to do t = NewsBase(key=news_key('finagnews'))?someone1

2 Answers

2
votes

You need the full key, including the ancestor if there is one. That's because the child ID by itself is not necessarily unique: only the full path is, so you need it to identify the particular entity.

In your case, you probably just want nb.Key('NewsBase', 'mynews', 'NewsBase', 8001).

(I suspect however that you are doing something strange to create your keys in the first place: it's unusual to have an ancestor, with a name key, of the same type as the numeric ID of the child.)

1
votes

Try using the urlsafe version of the key instead of the ID:

Output the key as:

key.urlsafe() instead of key.id()

and delete it in your request handler as:

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

the urlsafe version of the key will contain all necessary ancestor information.

Also, does your news_key function know that the key its making exists? You should not store an entity with a parent key for an entity that does not exist.

You're news_key should probably be something more like:

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

Just as an FYI - Deleting the parent does not delete all children. Also, the way you have it shown here, the Parent to your NewsBase entity will be another NewsBase entity.