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

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

问题描述

这看起来应该很简单,所以我一定遗漏了一些东西.我只想按名称设置模型实例中字段的值.说我有:

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()

我想通过名称设置 bar 的值,而不是通过访问字段.所以就像:

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

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

代替

f.bar = 'BAR'

我尝试过 setattr 但它不会将值保留在数据库中.我也尝试过 _meta.fields,但在此过程中遇到了各种错误.

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.

推荐答案

如果通过setattr修改值,修改后需要记得保存模型.过去我被咬了,我改变了值但忘记保存模型,得到了相同的结果.

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天全站免登陆