简体   繁体   中英

Get sum of other model field base on condition

I want to the get the sum of the total field of ru.invoice to be displayed on ru.students if the name field of ru.students is equal to student_id of ru.invoice .

I used the browse method but it does not work.

class ru_students(models.Model):
    _name = 'ru.students'
    _rec_name = 'code'

def _get_total(self, cr, uid, ids, context=None):
    pool_re = self.pool.get('ru.invoice')
    pool_rec = pool_re.browse(cr, uid, ids, [('name','=','student_id')],    
context=context)
    for field in self:
        for line in pool_rec:
            x = 0.0
            x += line.total
            field.payed += x

    name = fields.Char(string="Name")
    payed = fields.Float(compute="_get_total")


   class ru_invoice(models.Model):
       _name = 'ru.invoice'
       _rec_name = 'code'

    @api.multi
    @api.depends('qty','unit_price')
    def get_total(self):
        for rec in self:
            x = 0.0
            x = rec.qty * rec.unit_price
            rec.total = x


student_id = fields.Many2one('ru.students','Student ID")
qty = fields.Float(string="Quantity")
unit_price = fields.Float(string="Unit Price")
total = fields.Float(compute="_get_totals",string="Total")

First of all, be careful don't mix API7 code with API8 code, use always API8 code if you can (besides, it's going to be much easier for you to use API8). I think you want this on your field payed (check the class ru_invoice too because I corrected some things there - example: in total field you had written _get_totals in compute when you wanted to call _get_total -).

class ru_students(models.Model):
    _name = 'ru.students'
    _rec_name = 'code'

    @api.multi
    @api.depends('invoices')
    def _get_total(self):
        for student in self:
            student.payed = sum(
                invoice.total for invoice in student.invoices)

    name = fields.Char(string='Name')
    payed = fields.Float(compute='_get_total', string='Payed')
    invoices = fields.One2many(comodel_name='ru.invoice',
                               inverse_name='student_id',
                               string='Invoices of the student')


class ru_invoice(models.Model):
    _name = 'ru.invoice'
    _rec_name = 'code'

    @api.multi
    @api.depends('qty', 'unit_price')
    def _get_total(self):
        for invoice in self:
            invoice.total = invoice.qty * invoice.unit_price

    student_id = fields.Many2one(comodel_name='ru.students',
                                 string='Student ID')
    qty = fields.Float(string='Quantity')
    unit_price = fields.Float(string='Unit Price')
    total = fields.Float(compute='_get_total', string='Total')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM