【问题标题】:BadRequestError: Only ancestor queries are allowed inside transactionsBadRequestError:事务中只允许祖先查询
【发布时间】:2012-07-20 13:47:28
【问题描述】:
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() 上的标题错误将失败。

在我的脑海中,我想将一个新的子实体附加到我在事务中使用的单个父实体(如果它尚不存在),否则进行增量。为什么这不被视为祖先查询,我应该怎么做才能获得我想要的效果?

【问题讨论】:

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


    【解决方案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)
    

    【讨论】:

    • 你为什么要foo.all()...get().key()?如果您只需要密钥,请执行仅密钥查询。
    猜你喜欢
    • 2012-07-06
    • 1970-01-01
    • 2011-03-19
    • 2016-05-06
    • 2021-09-06
    • 2017-11-25
    • 2021-10-07
    • 1970-01-01
    • 2010-12-12
    相关资源
    最近更新 更多