Search code examples
pythonpython-2.7odoo-8odoo

How to order by two fields in Odoo 8?


I have a recordset of partners. Now I want to order this recordset by two attributes. One of this attributes is a simple Char, but the other one is a Many2one, which is a problem.

Example (suppose variable partners is the recordset):

  • This works: partners.sorted(key=lambda r: r.name) (with Char no problem).
  • This does not work: partners.sorted(key=lambda r: r.country_id) (with Many2one, you must add an attribute of the other model).
  • This works: partners.sorted(key=lambda r: r.country_id.id) (now we have indicated an attribute of res.country, the recordset is ordered rightly).

The problem is: I need to order by two fields, as I wrote above. For that it seems that I have to use itemgetter, but:

  • This does not work: partners.sorted(key=itemgetter('name', 'country_id')) (country_id is ignored, as when I tried to order by only this one above).
  • This gives an error: partners.sorted(key=itemgetter('name', 'country_id.id')) (the error message is that country_id.id is not a field of res.partner).
  • This seems to work: partners.sorted(key=itemgetter('name', 'phone')) (because both fields are Char).

I also tried to link two sorted in a row, this way:

partners.sorted(key=lambda r: r.name).sorted(key=lambda r: r.country_id.id)

But it is not working neither, because the second sorted function messes up the result of the first one.

Can anyone help me with this, please?


Solution

  • What about

    partners.sorted(key=lambda p: (p.name, p.country_id.id))