0

I am building a blog using GAE. i would like to delete specific posts stored in datastore with the ID key.My code being..

#my db model
class Post(db.Model):
subject = db.StringProperty(required = True)
content = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
lastmodified = db.DateTimeProperty(auto_now = True)

#my delete post handler
class DeletePost(Bloghandler):
    def post(self):
        key = self.request.get('id')

#my html form which passes the ID of the entity.
<form method="post" class="button-link" action="http://localhost:8080/blog/delete">
<input type="hidden" name="id" value={{p.Key().id()}}>
<input type="submit" name="delete" value="Delete">
</form><br><br>

there was a similar post to delete entities which had involved blobstore, that made it quite difficult for me to follow and implement. Any help would be greatly appreciated!:)

DeadDjangoDjoker
  • 534
  • 2
  • 8
  • 20

2 Answers2

1

db.delete(key)

I don't really understand your question besides that. If you have the key you just call db.delete using said key

what more do you need (if I was unclear on what you were asking)?

Patrice
  • 4,641
  • 9
  • 33
  • 43
  • i tried doing that, it din work.I have the id for that row and not the key. how do i continue from this point to delete that partiucular row?? – DeadDjangoDjoker Jul 31 '14 at 09:17
  • from the id, can't you do something like "MyModel.get_by_id([your id])", to get your entity, and then do key = entity.key() to get the key (no brackets if you're using ndb instead of db). https://docs.google.com/document/d/1AefylbadN456_Z7BZOpZEXDq8cR8LYu7QgI7bt5V0Iw/mobilebasic (very helpful webpage to see db V ndb and their methods) – Patrice Jul 31 '14 at 13:10
1

There is no need to actually get the entity from Datastore in order to delete it. Since you have the id of the key, you can just construct it manually using Key.from_path

class DeletePost(Bloghandler):
  def post(self):
    key_id = self.request.get('id')
    db.delete(db.Key.from_path('Post', key_id))

Note that this and the other proposed solutions won't if you add a parent to your key, which may be important as you start to think about your consistency model.

Instead, you should use a serialized version of your key:

class DeletePost(Bloghandler):
    def post(self):
        key = db.Key(encoded=self.request.get('id'))
        db.delete(key)

<form method="post" class="button-link" action="http://localhost:8080/blog/delete">
<input type="hidden" name="id" value={{p.key()}}>
<input type="submit" name="delete" value="Delete">
</form><br><br>

As described here, using str() on a db.Key will return a urlsafe string encoding of the key that can then be read by the Key constructor.

Patrick Costello
  • 3,616
  • 17
  • 22