user3030969
user3030969

Reputation: 1575

How to substitute the following value?

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

Answers (1)

RemcoGerlich
RemcoGerlich

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

Related Questions