假设我创建了一个新实体,如下所示:
item = Item()
item.property = property_value
item_key1 = item.put()
问题1 :在此行之后的同一文件中,如果我执行以下操作会发生什么:
item_key2 = item.put()
现在,数据存储区是否有一个实体 - 项目,或数据存储区是否有两个实体分别由item_key1和item_key2标识?
问题2 :在此行之后的同一文件中(没有在问题1中添加代码),如果我执行以下操作会发生什么:
item.property = new_property_value
item.put()
数据存储区中的同一实体是否得到更新,或者数据存储区是否创建了一个属性等于new_property_value的新实体?
问题2的后续问题:如果数据存储区在这种情况下创建了两个实体,是否意味着我必须执行以下操作来更新实体,即使该实体刚刚在同一个函数中创建?
item = Item()
item.property = property_value
# entity written to datastore
item_key = item.put()
# get the entity from the datastore to make sure it is the entity to update
item = item_key.get()
# update the value
item.property = new_property_value
# put it back to datastore
item.put()
这看起来非常愚蠢,在数据存储区写入中花费了两倍。
感谢。
答案 0 :(得分:4)
你的两个问题的答案是你只有一个实体。
将实体放入数据存储区时,它始终使用相同的键覆盖现有实体。致电put()
后,您的商品就会有一个唯一的密钥。现在,同一项目上的每个后续put()
都将覆盖数据存储区中的现有实体。
在以下情况下,您将只有两个实体:
item = Item()
item_key1 = item.put()
item = Item()
item_key2 = item.put()