我尝试使用自己的密钥在数据存储区中创建记录:
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)
返回
BadKeyError:无效的字符串键z523068_139840081_879156。
由于它不起作用,我怎么知道为我的记录创建了哪个键? db.Key()
可以使用db.run_in_transaction
吗?我应该如何创建计数器第一次然后使用自动生成的密钥增加值?
更新。我也尝试了以下内容:
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)
答案 0 :(得分:3)
您传递的是key_name,因此您应该使用get_by_key_name
代替db.get
:
class Counter(db.Model):
counter = db.IntegerProperty()
def increase_counter(key_name):
obj = Counter.get_by_key_name(key_name)
if obj is None:
obj = Counter(key_name=key_name, counter=1)
else:
obj.counter += 1
return obj.put()
db.run_in_transaction(increase_counter, "z"+intValue1+"_"+intValue2+"_"+intValue3)
编辑。如果您确实需要传递密钥,可以使用:
def increase_counter(key, amount=1):
obj = db.get(key) if key else None
if obj:
obj.counter += amount
else:
obj = Counter(counter=amount)
return obj.put()
db_counter_key = None # initially we don't have key value
db_counter_key = db.run_in_transaction(increase_counter, db_counter_key,
amount=len(files_arguments))
(按照您的示例,您不需要运行多个事务,而是可以将amount
参数作为增量值传递)
请注意,您可以返回obj.put()
,因为put()
会返回实体密钥。