【问题标题】:In Google App Engine datastore (for Python), are ndb key ids by default always integers?在 Google App Engine 数据存储区(用于 Python)中,ndb 键 ID 默认情况下是否始终为整数?
【发布时间】:2016-01-13 23:15:27
【问题描述】:
似乎是这样,但我无法在文档中确认。
ndb Key class 包括方法id、string_id 和integer_id。在id 中,它指出:
返回最后一个 (kind, id) 对中的字符串或整数 id,如果键不完整,则返回 None。
我假设 string_id 仅在 Key 构造函数显式传递字符串 id 时返回有效 id。
【问题讨论】:
标签:
python
google-app-engine
google-cloud-datastore
app-engine-ndb
【解决方案1】:
我确认确实如此。它在文档here 中有说明(有些人可能会说,埋没):
应用程序可以在不指定 ID 的情况下创建实体; Datastore 会自动生成一个数字 ID。
代码示例:
from google.appengine.ext import ndb
class Fingerprint(ndb.Model):
fingerprint = ndb.StringProperty(required=True)
fingerprint = Fingerprint(fingerprint='abc')
new_key = fingerprint.put()
print new_key.id(), type(new_key.id())
fingerprint = Fingerprint(id='abc', fingerprint='abc')
new_key = fingerprint.put()
print new_key.id(), type(new_key.id())
fingerprint = Fingerprint(id=100, fingerprint='abc')
new_key = fingerprint.put()
print new_key.id(), type(new_key.id())
输出:
4785074604081152 <type 'long'>
abc <type 'str'>
100 <type 'long'>