How to Implement sorted + lambda in Odoo?
What is sorted()?
The sorted() function returns a new sorted list from the items in an iterable.
What is lambda?
lambda is used to create anonymous functions, often for simple operations like extracting sort keys.
✅ Syntax
sorted(iterable, key=lambda x: x.field_name)
- iterable: List or Odoo recordset
- key: A function (usually lambda) that returns the value to sort by
📌 Realistic Use Cases in Odoo
1. Sort Sale Orders by Total Amount
sorted_orders = sorted(self.env['sale.order'].search([]), key=lambda o: o.amount_total)
This returns a list of sale orders sorted by their amount_total in ascending order.
2. Sort Partners by Number of Sale Orders (Descending)
partners = self.env['res.partner'].search([])
sorted_partners = sorted(partners, key=lambda p: len(p.sale_order_ids), reverse=True)
This gives you partners with the most orders first.
3. Sort Product Variants by Attribute Value (e.g., Size)
variants = self.product_variant_ids
sorted_variants = sorted(variants, key=lambda v: v.product_template_attribute_value_ids.filtered(lambda a: a.attribute_id.name == 'Size').name)
This sorts product variants by their "Size" attribute value.
✅ Summary Table
Function | Purpose | Example Use Case |
sorted() | Return a sorted list | Order records, partners, products |
lambda in key | Define sort logic inline | Sort by amount, length, custom field |
reverse=True (optional) | Descending order | Sort by latest, highest, largest |