How To Use Lambda Function in Odoo

A lambda function is a Python expression used within a domain expression to specify more complex filtering criteria. It allows you to define inline functions on the fly, which are not bound to a specific name like regular functions. Instead, lambda functions can be used as anonymous functions for simple operations.

Lambda logo, actually.. half-life logo

For example :

price_unit = sum(self.order_line.filtered(lambda line:line.product_id.id == promotional_code.discount_line_product_id.id).mapped('price_unit')

the code above has the same functionality like :

price_unit = 0
for line in self.order_line:
    if line.product_id.id == promotional_code.discount_line_product_id.id:
        price_unit += line.price_unit

Breakdown :

The lambda function above, is a simplified way of the for loop. It has the same functionality to check if the product id is same with promotional product id, then it should self accumulate the price_unit variables. Both methods are valid and achieve the same result, which is to sum up the ‘price_unit’ values of order lines that have matching product IDs. The lambda function approach is more concise and uses functional programming concepts, while the for loop approach is more explicit and follows traditional procedural programming. You can choose the method that best fits your coding style and preference.


Leave a Reply

Your email address will not be published. Required fields are marked *