views:

483

answers:

2

I have done this in python file, but my records don delete from DB. My DB is at Google App engine. There will be only one record against this query. Any solution?

deleteContact = db.GqlQuery("SELECT * FROM FriendList WHERE myNum = :1 AND friendNum = :2", myId,friendId)
results = deleteContact.fetch(1)
for result in results:
  db.delete(result)
+1  A: 

Since there is only 1 record being returned you dont need the for loop but that shouldn't stop it. If you need to only get 1 record you can use the get() call. You can also bulk delete records if you pass the list into the db.delete() call. e.g.

db.delete(results) is the same as

for result in results:
  db.delete(result)

But back to your code. The code below should work

deleteContact = db.GqlQuery("SELECT * FROM FriendList WHERE myNum = :1 AND friendNum = :2", myId,friendId) 
result = deleteContact.get() 
db.delete(result)

That should delete the 1 record returned so you may want to check that you select is doing what you expect it to do.

AutomatedTester
db.delete(result) will throw an exception if result is None. Need to either check for it or use fetch() - which returns an empty list rather than none if no matching entities are found
wf
A: 

The code in the question looks like it should work. Double check that a FriendList entity which matches the select statement actually exists in the datastore.

Some suggestions:

deleteContact = db.GqlQuery("SELECT __key__ FROM FriendList WHERE myNum = :1 AND friendNum = :2", myId,friendId)
result = deleteContact.get()
if result is not None:
  db.delete(result)
else:
  logging.error('result was None')

Since you aren't doing anything else with the results, only retrieving the keys from the datastore will be more efficient. Not a big deal here since you're only getting 1 result, but it's something to be aware of if you later need to delete a large number of entities from the datastore.

Since you only need one record, calling deleteContact.get() will only retrieve one, but it will return None if there were no matching entities. db.delete() will throw BadArgumentError if you pass it None, so make sure to test for it.

Alternatively, deleteContact.fetch(1) will return an empty list if there are no matching entities, which is fine to pass to db.delete(). But if you want to ensure that an entity was actually found you would need to make sure the list you got from fetch() did not have a length of 0.

wf