Tutorial :djangoproject access fields of object dynamically



Question:

Can anyone help me?

I have list of fields called 'allowed_fields' and I have object called 'individual'.
allowed_fields is sub set of individual. Now I want to run loop like this

for field in allowed_fields:
obj.field = individual.field

obj have same fields like individual. Do you have solution of my problem? I will thankful to you.


Solution:1

If each field is actually a string, you could try the following.
I renamed field to fieldname to better indicate that it is a string.

for fieldname in allowed_fields:      setattr(obj, fieldname, getattr(individual, fieldname))  


Solution:2

setattr(obj, fieldname, fieldvalue)

(see also getattr to retrieve at runtime)


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »