如何按名称设置django模型字段? [英] How to set django model field by name?
问题描述
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屋!