无法从数据存储区实体访问ID属性

jbm*_*sso 7 python google-app-engine entity google-cloud-datastore

使用Google App Engine SDK和Python,我遇到了一个问题:我无法访问给定实体属性的ID属性.我可以访问的唯一属性是我的类Model中定义的属性,以及key属性(请参阅下面的答案):

class Question(db.Model):
    text = db.StringProperty()
    answers = db.StringListProperty()
    user = db.UserProperty()
    datetime = db.DateTimeProperty()
Run Code Online (Sandbox Code Playgroud)

我可以很好地访问文本,答案,用户,日期时间和关键属性.但是,我无法访问ID属性.例如,在获取所有实体之后(使用Question.all()):

# OK Within a template, this will return a string :
{{ question.text }}
# OK, this will return the entity key :
{{ question.key }}

# KO this will return nothing :
{{ question.id }}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗 ?谢谢 !

ber*_*nie 11

根据文档,没有id()为Model子类定义实例方法.

试试吧{{ question.key }}.

另请注意,在将实体保存到数据存储区之前,不会创建密钥.


编辑:基于OP编辑的更多信息:

由于我们真的在数字ID之后,我们可以在模板中执行以下操作:

{{ question.key.id }}

另一个注意事项:您永远不应期望数字ID的值增加与实体创建的顺序相对应.在实践中,这通常是 - 但并非总是如此 - .


jbm*_*sso 5

我刚刚发现了一个可能的(不优雅的,IMO)解决方案.查询并获取实体后,遍历所有实体并手动添加id参数:

query = Question.all()
questions = query.fetch(10)

# Add ID property :
for question in questions:
    question.id = str(question.key().id())
Run Code Online (Sandbox Code Playgroud)

我不认为它是高效的CPU,但它可以作为快速/脏的修复.