无法从数据存储实体访问ID属性 [英] Unable to access ID property from a datastore entity

查看:68
本文介绍了无法从数据存储实体访问ID属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  class问题(db.Model):
text = db.StringProperty()
answers = db.StringListProperty()
user = db.UserProperty()
datetime = db.DateTimeProperty()

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

 #OK在模板中,这将返回一个字符串:
{{question.text}}
#OK,这将返回实体键:
{{question.key}}

#KO这将不会返回任何想法?
{{question.id}}

感谢!

根据 docs / python / datastore / modelclass.htmlrel =noreferrer> documentation ,没有为模型定义的 id()实例方法



尝试 {{question.key}}

另请注意,直到实体保存到数据存储区时才会创建密钥。




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



因为我们真的在数字ID 之后,我们可以在模板中做这样的事情:



{{question.key.id}}



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


Using Google App Engine SDK and Python, I'm facing an issue : I'm unable to access the ID property of a given entity properties. The only properties I can access are those defined in my class Model, plus the key property (see answer below) :

class Question(db.Model):
    text = db.StringProperty()
    answers = db.StringListProperty()
    user = db.UserProperty()
    datetime = db.DateTimeProperty()

I can access text, answers, user, datetime and key properties just fine. However, I can't access the ID property. For example, after fetching all entities (using 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 }}

Any ideas ? Thanks !

解决方案

According to the documentation, there is no id() instance method defined for Model subclasses.

Try {{ question.key }} instead.

Also note that the key is not created until the entity is saved to the datastore.


Edit: more info based on OP's edit:

Since we're really after the numeric ID, we could do something like this in our template:

{{ question.key.id }}

Another note: you should never expect numeric IDs to increase in value corresponding with the order of entity creation. In practice, this is usually—but not always—the case.

这篇关于无法从数据存储实体访问ID属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆