How to Implement hasattrs & getattrs in Odoo?

In Odoo development, we often deal with dynamic models and objects. Python built-in functions `hasattr()` and `getattr()` help us safely access attributes without raising errors.


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')


2. getattr()

`getattr(object, name[, default])` is used to retrieve the value of the specified attribute. If the attribute does not exist, it raises an `AttributeError` unless a default value is provided.


Example: Using getattr() in Odoo

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)


Combined Use Case in Odoo

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}")


Conclusion

`hasattr()` and `getattr()` are essential tools for writing flexible, error-free, and dynamic code in Odoo. They allow developers to check and retrieve fields on models at runtime, making the code adaptable to changes.