I tried to create the record in the datastore with my own key:
class Counter(db.Model):
counter = db.IntegerProperty()
def increase_counter(key):
obj = db.get(key)
if obj is None:
obj = Counter(key_name=key, counter=1)
else:
obj.counter += 1
obj.put()
db.run_in_transaction(increase_counter, "z"+intValue1+"_"+intValue2+"_"+intValue3)
It returns
BadKeyError: Invalid string key z523068_139840081_879156.
Since it doesn’t work, how can I know which key is created for my record? Can db.Key() can be used with db.run_in_transaction? How should I create counter first time and then increase the value with automatically generated key?
Upd. I’ve also tried the following:
def increase_counter(key):
if key is None:
obj = Counter(counter=1)
else:
obj = db.get(key)
obj.counter += 1
obj.put()
return obj.key()
db_counter_key = None # initially we don't have key value
for argument in files_arguments:
db_counter_key = db.run_in_transaction(increase_counter, db_counter_key)
You are passing a key_name, so you should use
get_by_key_nameinstead ofdb.get:Edit. If you really need to pass a key, you can use this:
(following your example, you don’t need to run multiple transactions and can instead pass an
amountargument as the increment value)Notice that you can return
obj.put(), becauseput()returns the entity key.