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

时间:2010-02-07 22:45:26

标签: 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()

我可以很好地访问文本,答案,用户,日期时间和关键属性。但是,我无法访问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 }}

有什么想法吗?谢谢!

2 个答案:

答案 0 :(得分:11)

根据 documentation ,没有为模型子类定义id()实例方法。

请尝试{{ question.key }}

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


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

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

{{ question.key.id }}

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

答案 1 :(得分:5)

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

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

# Add ID property :
for question in questions:
    question.id = str(question.key().id())

我认为它不是高效的CPU,但它可以作为一个快速/肮脏的解决方案。