[Answer]-Getting dynamic values from an object

1👍

dirty_fields will be a dictionary of changed fields. eg

{'boolean': True, 'characters': 'testing'}

When you iterate using for field in dirty_fields, field refers to the dictionary key, eg 'boolean' and 'characters'. You cannot use self.field because this will attempt an attribute lookup name field on your instance.

Instead, you need to take the field key value, and ask that this field be looked up on the instance of self using getattr().

Try this:

new_values = ['{0}: {1}'.format(field, getattr(self, field)) for field in dirty_fields] 

Leave a comment