对创建该实体的 @classmethod 中的实体的更新无法可靠地保留在数据存储中。
我的创建方法如下。参数为需要持久化的对象。
@classmethod
def create(cls, obj):
"""Factory method for a new system entity using an System instance. Returns a System object (representation) including the meta_key."""
if isinstance(obj, System):
pass
else:
raise Exception('Object is not of type System.')
#check for duplicates
q = dbSystem.all(keys_only=True)
q.filter('meta_guid = ', obj.meta_guid)
if q.get(): #match exists already
raise Exception('dbSystem with this meta_guid already exists. Cannot create.')
# store stub so we can get the key
act = cls(
meta_status = obj.meta_status,
meta_type = obj.meta_type,
meta_guid = obj.meta_guid,
json = None,
lastupdated=datetime.datetime.now())
act.put()
# get the key for the datastore entity and add it to the representation
newkey = str(act.key())
# update our representation
obj.meta_key = newkey
# store the representation
act.json = jsonpickle.encode(obj)
act.put()
return(obj) #return the representation
我的单元测试确认返回的对象有一个meta_key,并且关联实体的json不是none:
self.assertIsNotNone(systemmodel.dbSystem().get(s.meta_key).json) #json is not empty
但是,当在开发服务器上运行我的应用程序时,我发现稍后检索该实体时,json 字段间歇性为 NULL。
我花了一些时间研究数据存储模型,试图找到一些可以解释不一致结果的东西,但没有成功。两个关键来源是model class和一个非常好的overview of the App Engine datastore我在谷歌代码上找到了。
任何人都可以确认对创建实体的 @classmethod 中的实体的更新是否应该被认为是可靠的?有没有更好的方法来持久保存对象的表示?
最佳答案
问题可能出在这一行:
q = dbSystem.all(keys_only=True)
您还没有说明 dbSystem
是什么,但如果它执行应用程序引擎查询,则不能保证您获得对象的最新版本,并且您可能会获得旧版本。
相反,您应该通过对象的键来获取该对象,这将保证您获得最新版本。像这样的事情:
q = dbSystem.get(obj.key())
查看应用引擎文档以通过其键获取对象。
关于python - @classmethod 可以修改它在 GAE 中创建的记录吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26193612/