This question has been flagged
2 Replies
23799 Views

Hello, I was wondering if there is an easy way to sort a many2one field in descending order?  Is it in the python file or xml view?  I tried adding an _order = 'field_name desc' in the python class file, but it didnt work.  Thank you 

Avatar
Discard
Best Answer

_order = 'field_name desc' in the model should normally work but it applies for all views of your application
If you want to specify the order only in that many2one field, one solution is to use a context value and overwrite the search function:

f.i.:

In my python class:
    period_id = fields.Many2one(string='Period',
                                                       comodel_name='account.period')

In my XML view
    <field name="period_id"  context="{'order_display': 'name desc' }"/>

In the python model of the comodel:
    class AccountPeriod(models.Model):
        _inherit = 'account.period'
        @api.model
        def search(self, args, offset=0, limit=None, order=None, count=False):
            ctx = self._context
            if 'order_display' in ctx:
                order = ctx['order_display']
            res = super(AccountPeriod, self).search(
                args, offset=offset, limit=limit, order=order, count=count)
            return res

Avatar
Discard

Tjanks Johan, work like a charm :)

Best Answer

To add your code in the many2one master table in the python file for the name fields or other fields that are using to display value in the drop down list

Avatar
Discard