Lets say this is my model
class A(models.Model):
name = models.CharField(max_length=10)
And I have this list:
l = ['name']
I want to do this:
a = A()
a.l[0] = 'Jack'
Why doesn't python substitute name
from the list
such that it becomes a.name
? TIA
Because Python looks up al
, and if it were to find that, it would try to set its first element.
You're looking for setattr:
setattr(a, 'name', 'Jack')
or
setattr(a, l[0], 'Jack')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.