使用动态字段名称更新模型实例 [英] Update model instance with dynamic field names

查看:73
本文介绍了使用动态字段名称更新模型实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的很简单:

f=Foobar.objects.get(id=1)
foo='somefield'
bar='somevalue'
f.foo=bar
f.save()

这不起作用,因为它尝试更新f对象的'foo'字段,该字段当然不存在。我该怎么做?

This doesn't work as it tries to update the f object's 'foo' field, which of course doesn't exist. How can I accomplish this?

推荐答案

您可以使用 setattr

You can use setattr:

f = Foobar.objects.get(id=1)
foo = 'somefield'
bar = 'somevalue'
setattr(f, foo, bar) # f.foo=bar
f.save()




[ setattr ]是 getattr()的副本。参数是对象,字符串和任意值。该字符串可以命名现有属性或新属性。如果对象允许,该函数将值分配给属性。

[setattr] is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it.

这篇关于使用动态字段名称更新模型实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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