5

我的问题是,创建新模型实体的最佳方法是什么,然后立即阅读。例如,

class LeftModel(ndb.Model):
    name = ndb.StringProperty(default = "John")
    date = ndb.DateTimeProperty(auto_now_add=True)

class RightModel(ndb.Model):
    left_model = ndb.KeyProperty(kind=LeftModel)
    interesting_fact = ndb.StringProperty(default = "Nothing")

def do_this(self):
    # Create a new model entity
    new_left = LeftModel()
    new_left.name = "George"
    new_left.put()

    # Retrieve the entity just created
    current_left = LeftModel.query().filter(LeftModel.name == "George").get()

    # Create a new entity which references the entity just created and retrieved
    new_right = RightModel()
    new_right.left_model = current_left.key
    new_right.interesting_fact = "Something"
    new_right.put()

这通常会引发异常,例如:

AttributeError: 'NoneType' object has no attribute 'key'

即新LeftModel 实体的检索不成功。我在 appengine 中遇到过几次这个问题,而我的解决方案总是有点 hacky。通常我只是把所有东西都放在一个 try except 或一个 while 循环中,直到成功检索到实体。如何确保始终检索模型实体而不冒无限循环的风险(在 while 循环的情况下)或弄乱我的代码(在 try except 语句的情况下)?

4

1 回答 1

9

为什么在执行put().

您应该使用new_left刚刚创建的并立即将其分配给 new_right ,如new_right.left_model = current_left.key

您无法立即查询的原因是因为 HRD 使用最终一致性模型,这意味着您的 put 结果最终将是可见的。如果你想要一个一致的结果,那么你必须执行祖先查询,这意味着在创建键中有一个祖先。鉴于您正在创建一棵树,这可能不切实际。阅读有关为强一致性构建数据的信息https://developers.google.com/appengine/docs/python/datastore/structuring_for_strong_consistency

我看不出您为什么不使用刚刚创建的实体而不使用其他查询的任何原因。

于 2012-07-21T11:56:08.497 回答