python - 无法在数据存储区中检索具有生成 ID 的实体

标签 python google-cloud-datastore app-engine-ndb

我以非常简单的方式使用 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/

相关文章:

python - ndb 模型应用引擎的模型表单(django 表单不适合我)

python - 在 PySide 中强制 QTimer() 超时

Python,MySQLdb,无法更新行

python - 如果数组 0 发生更改,则保持数组大小不变

python - 如何匹配 'K' , 'M' , 'G' , 'Ki' , 'Mi' , 'Gi' 等但不是单独的 'i' 词缀

google-app-engine - 将照片存储在 Blobstore 中或作为 Blob 存储在数据存储中 - 哪个更好/更高效/更便宜?

java - 设置不同于类名的实体种类名称

python - NDB query() 是否通过缓存?

python - GAE Python NDB .put 在开发上不同步(但在生产中有效)?

python - 如何在 GAE Python NDB 中获取最新数据