[Tutor] Addressing a variable whose name is the value of a string
Kent Johnson
kent37 at tds.net
Mon Apr 9 18:04:08 CEST 2007
Andreas Pfrengle wrote:
> # Accessing db (see http://www.djangoproject.com/documentation/db-api/):
> myobj = MyModel.objects.get(<some filter>)
> var = myobj.vector
> # vector is a Textfield, so var now contains a string, naming another
> db-field of myobj
>
> execstr = "attr = myobj." + var
> exec execstr
> # attr now contains the content of the field named in var (an int in my
> case)
Use
attr = getattr(myobj, var)
> attr += 42 #some calculation with attr
>
> execstr = "myobj." + var + " = attr"
> exec execstr
setattr(myobj, var, attr)
Kent
More information about the Tutor
mailing list