Django模型字段由变量 [英] Django model field by variable
问题描述
快速问题。我正在尝试使用变量访问模型的一个领域。
Quick question. I'm trying yo access one of the fields of a model using a variable.
class ExampleModel(models.Model):
the_field = models.CharField()
the_field_two = models.CharField()
如何动态访问该字段?我尝试:
How would access the field dynamically? I tried:
model = ExampleModel.objects.get(pk=1)
fieldtoget = 'the_field'
test_var = model[fieldtoget]
但是似乎不起作用,任何想法如何会这样做吗?
But it doesn't seem to work, any ideas how I would do this?
更新:想到我会更新我的问题。我正在尝试编写一个函数(作为大函数的一部分),它不仅可以获取字段的值,还可以从变量字段名更新它。例如:
Update: Thought I'd update my question. I'm trying to write a function (as part of larger function) that can not only get the value of the field but also update it from a variable fieldname. For example:
model[fieldtoget] = 'yo'
model.save()
在PHP中,您可以使用{}包装器 - $ model {$ fieldtoget}
- 作为一个例子,动态变量名希望在python中有类似的东西:)
In PHP you can use the {} wrapper - $model{$fieldtoget}
- as an example, for dynamic variable names was hoping there was something similar in python :)
Cheers
推荐答案
您可以使用pythons getattr函数来做到这一点。将字段名称作为属性传递。
You can use pythons getattr function to do this. Pass the field name in as the attribute.
getattr(model, fieldtoget)
由于fieldtoget是一个变量,这是动态的。
Since fieldtoget is a variable, this is dynamic.
您可以使用setattr设置它同样的方式。
You can use setattr to set it the same way.
这篇关于Django模型字段由变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!