Boris Burkov
Boris Burkov

Reputation: 14446

Django: how to get field by field name from Model instance dynamically?

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.

Upvotes: 15

Views: 13235

Answers (1)

Muhammad Hassan
Muhammad Hassan

Reputation: 14391

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)

Upvotes: 26

Related Questions