The sorted() function in Odoo is commonly used to sort a
recordset based on a particular field or condition, much like
Python's built-in sorting functionality. It takes three main
parameters:
- The first is the recordset or iterable to be sorted.
- The second is a key function, often written as a lambda
expression, which determines the sorting logic—for example,
using lambda rec: str(rec.name).lower() to sort records
alphabetically, ignoring case.
- The third parameter, reverse, is a boolean that controls
the sorting order, where True sorts in descending order and
False in ascending order.
This method is especially useful when you need to sort records in
memory after retrieving them from the database.
partners = self.env['res.partner'].search([])
partners.sorted(lambda o: o.create_date, reverse=True)
Now, the partners variable contains the records of partners sorted by
their create_date field, either in ascending or descending
order, depending on your preference.