How to Implement hasattrs & getattrs in Odoo?
1. hasattr()
`hasattr(object, name)` checks whether the given object has an attribute with the specified name.
Returns:
– `True` if the attribute exists
– `False` otherwise
Example: Using hasattr() in Odoo
Assume we are working with different models, and we want to perform an operation only if a specific field exists:
if hasattr(record, ’email’):
print(‘Email:’, record.email)
else:
print(‘No email field found’)
We want to access an attribute dynamically (based on user input or configuration):
field_name = ’email’
email_value = getattr(record, field_name,‘Not Available’)
print (‘Email:’, email_value)
These functions are very helpful when writing generic code across models or handling optional fields:
def print_attribute(record, field):
if hasattr(record, field):
print(f “{field}: {getattr(record, field)}”)
else:
print(f ‘{field} not found on record of model {record._name}’)