Skip to Content
Menu
This question has been flagged

Hi there,

I have a list of records created in this model:


class VLabelProductionSite(models.Model):

    _name = "vlabel.production.site"

    audit_ids = fields.One2many('vlabel.audit', 'related_production_site', string='Audit ID')

    state = fields.Selection([

        ('new', 'New'),

        ('wip', 'Audit in Progress'),

        ('done', 'Audit Done')

    ], string='Audit Status', default='new', track_visibility='always')


This other model looks like this and has these fields:

class VLabelAudit(models.Model):

    _name = "vlabel.audit"

    audit_date = fields.Date(string="Audit Date")

    related_production_site = fields.Many2one('vlabel.production.site',

                                              string='Production Site', required=True)


In a tree view for vlabel.production.site I want to show the date of the audit_id that has the lastest audit_date, filtered for self. If I have three records in vlabel.production.site I want in the tree view for each record to show that latest audit date.


So if there is record1 in vlabel.production.site and it has 4 related records in the vlabel.audit, I want to show the audit_date from the audit that happened last for that record (self)


I tryied for hours trying to get related records of self but didn't manage, this is my solution so far in the vlabel.production.site model


def get_last_audit_date(self):

        for rec in self:

            audits = self.env['vlabel.audit'].search([('related_production_site', '=',          production_site.id), ('state', '=', 'done')])

            last_audit = audits[-1]

        return last_audit.audit_date

 

I am very grateful for any help. Happy holidays to you all.

Avatar
Discard
Best Answer

Hello Adrian,

I would suggest doing the date as a computed field as such:

last_audit_date = fields.Date(string="Last Date", compute="_last_date_compute")
@api.depends("audit_ids.audit_date")
def _last_date_compute(self):
    for record in self:
        record.last_audit_date = max([audit.audit_date for audit in record.audit_ids])

This will get the last audit date of all the records in audit_ids. 

I hope this solves your issues.

Thanks, 

Avatar
Discard
Author

Thx alot Jack, you already made my day. Way better than forcing the search. All the best,

Adrian

Related Posts Replies Views Activity
3
Oct 23
2549
1
Mar 23
783
0
Dec 22
1509
0
Jun 21
1838
0
Jun 20
4179