简体   繁体   English

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. 我正在尝试编写一个函数(作为更大函数的一部分),它不仅可以获取字段的值,还可以从变量fieldname更新它。 For example: 例如:

model[fieldtoget] = 'yo'
model.save()

In PHP you can use the {} wrapper - $model{$fieldtoget} - as an example, for dynamic variable names was hoping there was something similar in python :) 在PHP中,您可以使用{}包装器 - $model{$fieldtoget} - 作为示例,对于动态变量名称希望在python中有类似的东西:)

Cheers 干杯

You can use pythons getattr function to do this. 您可以使用pythons getattr函数来执行此操作。 Pass the field name in as the attribute. 将字段名称作为属性传递。

getattr(model, fieldtoget)

Since fieldtoget is a variable, this is dynamic. 由于fieldtoget是一个变量,因此这是动态的。

You can use setattr to set it the same way. 您可以使用setattr以相同的方式设置它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM