Search code examples
odoo-11one2many

one2many field get row number


I have a module contain one2many filed.

while I create data line in this o2m field, I'd like to append a row number to it.

I have try some method that I found in forum, like this link.

but since I have no function called _onchange_partner_id() , I don't know how to use it.

or this link .

but it seems like an old version method that I can't get well.

class YcWeight(models.Model):

    _name = "yc.weight"
    customer_detail_ids = fields.One2many("yc.weight.details", "name", "customer details")

class YcWeightDetails(models.Model):
    _name = "yc.weight.details"

    name = fields.Many2one("yc.weight", "weight detail list", ondelete="cascade")
    no = fields.Integer("row number")

the "no" is a field that I want to show number of row count. my problem is :

how can I get get the number of rows?

since onchage decorated function can't get data from db.


Solution

  • I find a solution by myself and it is simple:

    use depends decorator.

    class YcWeightDetails(models.Model):
        _name = "yc.weight.details"
    
        name = fields.Many2one("yc.weight", "weight detail list", ondelete="cascade")
        no = fields.Integer("row number")
        compuute_no = fields.Integer("invisible field", compute= "_get_row_no")
    

    create a field "compuute_no" to compute.

        @api.depends("compuute_no")
        def _get_row_no(self):
            if self.ids:
                count =1
                for rec in self:
                    weight_id = self.env['yc.weight.details'].search([('id','=', rec.id)])
                    weight_id.write({'no': count})
                    count+=1
    
    

    or overwrite create method

    @api.model
        def create(self, vals):
            main_key = self.env["yc.weight"].search([], order="id desc", limit=1).id
            item_key = vals["name"]
            if item_key and main_key == item_key:
                number = len(self.env["yc.weight.details"].search([("name", "=", item_key)]))
                vals.update({"no": number + 1})
                return super(YcWeightDetails, self).create(vals)
    

    hope it can help you.