开发者

How to get the key of created with db.run_in_transaction record?

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开发者_JS百科.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_name instead of 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)

Edit. If you really need to pass a key, you can use this:

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))

(following your example, you don't need to run multiple transactions and can instead pass an amount argument as the increment value)

Notice that you can return obj.put(), because put() returns the entity key.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜