Sorting recordsets
When you fetch a recordset with the search()
method, you can pass an optional argument order to get a recordset that's in a particular order. This is useful if you already have a recordset from a previous bit of code and you want to sort it. It may also be useful if you use a set operation to combine two recordsets, for example, which would cause the order to be lost.
This recipe shows you how to use the sorted()
method to sort an existing recordset. We will sort books by release date.
Getting ready
We will reuse the library.book
model that was shown in the Creating new records recipe in this chapter.
How to do it...
You need to perform the following steps to get the sorted recordset of books based on release_date
:
- Define a method called
sort_books_by_date()
:@api.model def sort_books_by_date(self, books):
- Use the
sorted()
method, as in the given example, to sort book records based on...