【问题标题】:Google App Engine: how can I programmatically access the properties of my Model class?Google App Engine:如何以编程方式访问模型类的属性?
【发布时间】:2010-09-10 15:31:35
【问题描述】:

我有一个模型类:

class Person(db.Model):
  first_name = db.StringProperty(required=True)
  last_name = db.StringProperty(required=True)

我在p 中有一个此类的实例,字符串s 包含值'first_name'。我想做类似的事情:

print p[s]

p[s] = new_value

这两个结果都是TypeError

有人知道我怎样才能实现我想要的吗?

【问题讨论】:

  • dir(p) 显示什么?

标签: python string google-app-engine


【解决方案1】:

p.first_name = "新名字" p.put()

或 p = Person(first_name = "Firsty", 姓氏=“最后”) p.put()

【讨论】:

    【解决方案2】:

    非常感谢 Jim,我正在寻找的确切解决方案是:

    p.properties()[s].get_value_for_datastore(p)
    

    感谢所有其他受访者的帮助。我也希望 Model 类能够实现 python 标准的方式来执行此操作,但无论出于何种原因,它都没有。

    【讨论】:

    • 为什么要使用 get_value_for_datastore?如果您想要从 p.first_name 获得的相同表示,则不应调用它。
    • 你问题的第二部分怎么样?那么 p[s] = new_val 呢?
    【解决方案3】:

    如果模型类足够智能,它应该能够识别标准的 Python 方法。

    试试:

    getattr(p, s)
    setattr(p, s, new_value)
    

    还有 hasattr 可用。

    【讨论】:

    • Dave,db.Model 和 db.Expando 类之间是否可能存在差异?
    【解决方案4】:

    试试:

    p.model_properties()[s].get_value_for_datastore(p)
    

    the documentation

    【讨论】:

    • 这样行吗? model_properties 是类方法,不是实例方法。
    • 谢谢你,你让我走上了正确的道路。确切的答案是 p.properties()[s].get_value_for_datastore(p)
    【解决方案5】:
    getattr(p, s)
    setattr(p, s, new_value)
    

    【讨论】:

    • 嗨,吉姆,感谢您的回复。上面的代码导致 AttributeError。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-29
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2015-07-01
    相关资源
    最近更新 更多