我以非常简单的方式使用 Google Cloud Datastore,并尝试通过实体 ID 检索实体。我读过this (它是用 Java 编写的,但似乎遵循相同的逻辑)
我的实体的定义在这里:
class Logs(ndb.Model):
startDate = ndb.DateTimeProperty()
endDate = ndb.DateTimeProperty()
requestedDate = ndb.DateProperty()
taskName = ndb.StringProperty()
status = ndb.StringProperty()
然后当我插入一个新的时,我会这样做
logs = Logs(startDate=datetime.utcnow(),
taskName=taskName,
requestedDate=requestedDate,
status=u'IN_PROGRESS')
key = logs.put()
id = key.id() # I use this variable later
当我想检索它时
logs = Logs.get_by_id(id)
但它永远不会返回任何实体...
这有什么问题吗?
感谢您的帮助
最佳答案
根据documentation ,您应该能够直接从 Key 对象调用 get() 以从数据存储区检索实体:
logs_entity = Logs(startDate=datetime.utcnow(),
taskName=taskName,
requestedDate=requestedDate,
status=u'IN_PROGRESS')
# Saves entity to Datastore and returns Key
entity_key = logs_entity.put()
# Retrieves entity from Datastore using the previous Key
result = entity_key.get()
编辑:
如果您需要将 key 作为字符串传递以稍后重建 Key 对象,您可以尝试使用 urlsafe() 方法,该方法允许将其嵌入 URL 中:
urlsafe_string = entity_key.urlsafe()
[...]
entity_key= ndb.Key(urlsafe=urlsafe_string)
logs_entity = entity_key.get()
关于python - 无法在数据存储区中检索具有生成 ID 的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48985477/