Reputation: 1575
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
Upvotes: 0
Views: 46
Reputation: 31260
Because Python looks up a.l
, 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')
Upvotes: 3