我想将位置存储在Google的数据存储区中。每个条目都应有“sys”字段,其中包含数据存储区设置的信息。
我有下面的类模型,WebService JSON请求/响应看起来没问题,但我必须手动设置值。看起来auto_current_user_add
,auto_now_add
,auto_current_user
和auto_now
不会触发。
from google.appengine.ext import ndb
from endpoints_proto_datastore.ndb import EndpointsModel
class Created(EndpointsModel):
by = ndb.UserProperty(auto_current_user_add=True)
on = ndb.DateTimeProperty(auto_now_add=True)
class Updated(EndpointsModel):
by = ndb.UserProperty(auto_current_user=True)
on = ndb.DateTimeProperty(auto_now=True)
class Sys(EndpointsModel):
created = ndb.StructuredProperty(Created)
updated = ndb.StructuredProperty(Updated)
class Location(EndpointsModel):
name = ndb.StringProperty(required=True)
description = ndb.TextProperty()
address = ndb.StringProperty()
sys = ndb.StructuredProperty(Sys)
当我提交创建请求(location.put()
)时,我收到以下回复:
{
"id": "4020001",
"name": "asdf"
}
当我使用以下方式手动设置时:
location.sys = Sys(created=Created(on=datetime.datetime.now(),
by=current_user),
updated=Updated(on=datetime.datetime.now(),
by=current_user))
location.put()
我得到了预期的结果:
{
"id": "4020002",
"name": "asdf",
"sys": {
"created": {
"by": {
"auth_domain": "gmail.com",
"email": "decurgia@XYZ"
},
"on": "2015-01-27T16:05:41.465497"
},
"updated": {
"by": {
"auth_domain": "gmail.com",
"email": "decurgia@XYZ"
},
"on": "2015-01-27T16:05:41.465577"
}
}
}
如何自动设置这些字段(sys.created.on
,sys.created.by
,sys.updated.on
,sys.updated.by
?
答案 0 :(得分:1)
在我使用StructuredProperty
的有限工作中,我发现它比简单地将属性直接插入模型更慢,更难以使用。 NDB似乎分别存储这些属性并执行" join"检索它们时。我的建议是使用" flat"模型:
class Location(EndpointsModel):
name = ndb.StringProperty(required=True)
description = ndb.TextProperty()
address = ndb.StringProperty()
created_by = ndb.UserProperty(auto_current_user_add=True)
created_on = ndb.DateTimeProperty(auto_now_add=True)
updated_by = ndb.UserProperty(auto_current_user=True)
updated_on = ndb.DateTimeProperty(auto_now=True)
这会导致auto_
属性自动触发。