BadRequestError:在事务内只允许祖先查询

时间:2012-07-21 15:57:21

标签: google-app-engine transactions google-cloud-datastore

from google.appengine.ext import db

class Parent(db.Model):
    app_id = db.StringProperty()

class Child(db.Model):
    app_id = db.ReferenceProperty(Parent,collection_name='children')
    type = db.StringProperty()
    count = db.IntegerProperty()

@db.transactional
def increment_counter(app,childName):
    childA = Child.all().ancestor(app).filter('type =',childName).get()
    if  childA is not None:
        obj = db.get(childA.key())
        obj.count += 1
        obj.put()
    else:
        childA = Child(app_id=app.key(),type=childName,count=0)
        childA.put()

increment_counter(Parent.all().filter('app_id =',app_id).get().key(),childKey)

如果childA为空,则失败,并在put()上出现标题错误。

在我的脑海中,我想将一个新的子实体附加到我在事务中处理的单个父实体(如果它尚未存在),否则执行增量。为什么这不被视为祖先的查询,我应该做些什么而不是为了获得我所追求的效果?

1 个答案:

答案 0 :(得分:1)

好的,似乎在离开App Engine一段时间之后我混淆了实体父和ReferenceProperty的单独概念。

正确的代码:

class Parent(db.Model):
    app_id = db.StringProperty()

class Child(db.Model):
    type = db.StringProperty()
    count = db.IntegerProperty()

@db.transactional
def increment_counter(app,childName):
    childA = Child.all().ancestor(app).filter('type =',childName).get()
    if  childA is not None:
        obj = db.get(childA.key())
        obj.count += 1
        obj.put()
    else:
        childA = Child(parent=app,type=childName,count=0)
        childA.put()

increment_counter(Parent.all().filter('app_id =',app_id).get().key(),childKey)
相关问题