Search code examples
odoo

Sort a tree view by Many2One field's display name, not ID


I do have a list that I want to sort by a field called hashtag_id that is a reference to another model.

That other model has a specific/complexe name_get and this is the return of that function that is displayed ot the user and that I do want to sort. (Note that the result of name_get is not stored in any other column)

View example:

<field name="list>
   <tree default_order="hashtag_id">
      <field name="hashtag_id">

Data example:

ID / result of name_get()
1 / JFOISEZOEIFJF
2 / RZELKRJREZIUH
3 / AERJEIOZJFDOI

What the user will see:

JFOISEZOEIFJF
RZELKRJREZIUH
AERJEIOZJFDOI

What I would like to display (notice the sort done):

AERJEIOZJFDOI
JFOISEZOEIFJF
RZELKRJREZIUH

How to make default_order="hashtag_id" sort by what's displayed and not by ID ?


Solution

  • You can change the default order field of hashtag model, the order field should be the field used for labeling records, default: name:

    _order = 'name'
    

    Or you can add a related field next to hashtag_id:

    hashtag_name = fields.Char(related="hashtag_id.name", store=True)
    

    Change the default order to hashtag_name and make the field invisible in the tree view:

    <tree default_order="hashtag_name">
        <field name="hashtag_id"/>
        <field name="hashtag_name" invisible="True"/>
    </tree>