【问题标题】:How to specify GAE Python ndb field name based on a variable如何根据变量指定 GAE Python ndb 字段名称
【发布时间】:2014-08-21 06:09:25
【问题描述】:

在将数据存储到 NDB 中时,我想从字符串变量(例如 field_name2 = "userid")中获取字段的名称。有办法吗?提前致谢。

class Account(ndb.Model):
     username = ndb.StringProperty()
     userid = ndb.IntegerProperty()

class MainPage():
    field_name2 = 'userid'

    acct = Account.get_key(id).get() 

    acct.username = "Bob"
    acct[**field_name2**] = "001"  ## How can I do something like this?
    acct.put()

【问题讨论】:

    标签: python google-app-engine google-cloud-datastore app-engine-ndb


    【解决方案1】:

    因为ndb.Models 的行为类似于普通的 Python 对象,您可以使用 Python getattrsetattr 动态访问字段。

    在你的例子中:

        setattr(acct, field_name2, "001")
    

    试一试http://shell.appspot.com 另见:How to dynamically access class properties in Python?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多