1. sum() — Add Values in Recordsets
✅ What is sum()?
The sum() function returns the total of numeric values in an iterable.
📌 Realistic Odoo Example
Suppose you want to calculate the total amount from a list of sale orders.
total_amount = sum(self.mapped('amount_total'))
- self is a recordset of sale.order
- mapped('amount_total') gives a list of totals
- sum() adds all the totals together
➕ More Example:
total_qty = sum(self.order_line.mapped('product_uom_qty'))
This gives the total quantity of all products in the order lines.
2. len() — Count Records or Items
✅ What is len()?
The len() function returns the number of items in a recordset or list.
📌 Realistic Odoo Example
Suppose you want to know how many order lines a sale order has:
line_count = len(self.order_line)
This returns the number of lines in the current order.
➕ More Example:
Count how many customers have at least one confirmed sale order:
partners = self.env['res.partner'].search([])
confirmed_partners = partners.filtered(lambda p: p.sale_order_ids.filtered_domain([('state', '=', 'sale')]))
count = len(confirmed_partners)
✅ Summary Table
Function | Purpose | Example Use Case |
sum() | Add numeric values | Total order amount, total quantity |
len() | Count number of items in record/list | Count lines, records, filtered partners |