【问题标题】:How to update existing model instance from dictionary value如何从字典值更新现有模型实例
【发布时间】:2013-11-09 08:45:07
【问题描述】:

给定模型实例,例如 StackOverflow 是模型, 和

 obj = StackOverflow.objects.get(..somecondition)
 dict  = { 'rating' : 3, 'field1' : 'question', field2 : 'answer' }

StackOverflow 模型将字典中可用的所有键作为成员变量。

我想用 dict 值更新 obj。

我怎样才能达到同样的效果?

【问题讨论】:

    标签: python django django-models django-forms django-views


    【解决方案1】:
    obj = StackOverflow.objects.get(pk=1)
    d  = { 'rating' : 3, 'field1' : 'question', 'field2' : 'answer' }
    
    for i in d:
        setattr(obj, i, d[i])
    obj.save()
    

    假设字典键对应于StackOverflow 模型中的字段,并且字典值是有效的字段值,这将起作用。

    【讨论】:

      【解决方案2】:

      尝试:

      d  = { 'rating' : 3, 'field1' : 'question', 'field2' : 'answer' }
      obj = StackOverflow.objects.filter(pk=1).update(**d)
      

      这里是doc

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-07
        • 2015-07-05
        • 2019-01-05
        • 1970-01-01
        • 2012-12-11
        相关资源
        最近更新 更多