【问题标题】:How do I mass assign attributes to model on google appengine / python?如何在 google appengine / python 上为模型批量分配属性?
【发布时间】:2012-12-16 15:55:38
【问题描述】:

我知道我可以在创建类时使用构造函数进行批量赋值:

attributes = {'name':'John', 'surname':'Smith', ...}
record = Model(**attributes)

但是当我有现有记录时如何分配属性?

record = ....
record.???(**attributes)

谢谢!

【问题讨论】:

    标签: python google-app-engine mass-assignment


    【解决方案1】:

    您只需分配给属性...

    mymodel = MyModel()
    mymodel.name = 'John'
    mymodel.surname = 'Smith'
    

    如果您想实际执行初始化程序所做的事情,那么您可以使用setattr

    attributes = {'name':'John', 'surname':'Smith'}
    record = Model()
    
    for k, v in attributes.iteritems():
        setattr(record, k, v)
    

    见:https://developers.google.com/appengine/docs/python/datastore/modelclass#Model

    从那里开始:

    应用程序通过实例化子类来创建新的数据实体 模型类的。可以使用分配实体的属性 实例的属性,或作为关键字参数 构造函数。

    s = Story()
    s.title = "The Three Little Pigs"
    
    s = Story(title="The Three Little Pigs")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 1970-01-01
      • 1970-01-01
      • 2012-02-18
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多