如何按名称设置django模型字段? [英] How to set django model field by name?

查看:72
本文介绍了如何按名称设置django模型字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎应该是死的简单,所以我一定是错过了一些东西。我只是想通过名称在我的模型实例中设置一个字段的值。说我有:

  class Foo(Model):
bar = CharField()

f = Foo()

我想按名称设置bar的值,而不是通过访问字段。所以这样的东西:

  f.fields ['bar'] ='BAR

而不是

  f.bar =' BAR'

我已经尝试过setattr,但它并没有保留数据库中的值我也尝试通过_meta.fields,但在路上遇到各种错误。

解决方案

如果您通过setattr修改值,则需要记得在修改后保存模型,过去我已经被改变了值,但忘了保存模型,并得到相同的结果。

  setattr(f,'bar','BAR')
f.save()


This seems like it should be dead simple, so I must be missing something. I just want to set the value of a field in my model instance by name. Say I have:

class Foo(Model):
  bar = CharField()

f = Foo()

I want to set the value of bar by name, not by accessing the field. So something like:

f.fields['bar'] = 'BAR"

instead of

f.bar = 'BAR'

I've tried setattr but it doesn't persist the value in the database. I also tried going through _meta.fields but got various errors along the way.

解决方案

If you modify the value via setattr, you need to remember to save the model after modifying it. I've been bitten in the past where I changed the values but forgot to save the model, and got the same result.

setattr(f, 'bar', 'BAR')
f.save()

这篇关于如何按名称设置django模型字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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