14

I have a model instance and a variable that contains name of the field that I have to print:

field_name = "is_staff"
user = User.objects.get(pk=0)

How do I get the value of that field by field_name? I can't just say user.is_staff, cause I can't hard-code that the field is called is_staff.

Importantly, I need to assign a value to the field, obtained this way: user.is_staff = True.

Boris Burkov
  • 13,420
  • 17
  • 74
  • 109
  • 1
    Use [`getattr`](https://docs.python.org/2/library/functions.html#getattr). What does this have to do with Django? Also, consider carefully why you're doing this. "Variable variables" are nearly always a code smell. – Two-Bit Alchemist May 11 '16 at 17:07
  • 2
    Possible duplicate of [getting dynamic attribute in python](http://stackoverflow.com/questions/13595690/getting-dynamic-attribute-in-python) – Two-Bit Alchemist May 11 '16 at 17:09

1 Answers1

23

Use can use `getattr'. It works like this

field_name = "is_staff"
user = User.objects.get(pk=0)
field_name_val = getattr(user, field_name)
Muhammad Hassan
  • 14,086
  • 7
  • 32
  • 54