我想将位置存储在 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
) 自动设置?
最佳答案
在我使用 StructuredProperty
进行的有限工作中,我发现它比简单地将属性直接插入到模型中更慢且更难使用。 NDB 似乎单独存储这些属性并在检索它们时执行“连接”。我的建议是使用“平面”模型:
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_
属性。
关于python - ndb.StructuredProperty 中的自动字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28168682/