Search code examples
odooodoo-8odoo-9

Filter lines by categ_id and count qty


My goal is to loop through all lines with the same categ_id and calculate total quantity they have and if qty_categ_total < categ_id.qty_for_discount ( I added this field to 'product.category' than I need to post a message in text fields. the problem my code is not working as I want.

Example.

If I have 2 lines with the same categ_id with qty 2 and 5 and my categ_id.qty_for_discount is 10. The message should say that I need to add 3 more products with the same categ_id to get discount

Update

And if there are products with different categories I should get a message for each category

class PurchaseOrder(models.Model):
    _inherit = 'purchase.order'

    discount_warning_message = fields.Text(string='Discount Warning', compute='discount_warning')

     @api.depends('order_line.product_id', 'order_line.product_qty')
def discount_warning(self):
    qty_categ_total = 0.0
    for line in self.order_line:
        qty_categ_total +=  line.product_qty
        if qty_categ_total < line.product_id.categ_id.qty_for_discount:
            message = (_("You can get discount if you add %s more %s\n")) % (qty_categ_total, line.product_id.categ_id.name)
            self.discount_warning_message = message

Solution

  • Your code seems to be correct, but i would change something. First either use @api.one to let odoo automatically loop through all orders or add one more for each loop and @api.multi. And secondly what about more than one category?

    @api.multi
    @api.depends('order_line.product_id', 'order_line.product_qty')
    def discount_warning(self):
        msg = _("You can get discount if you add %s more %s\n")
        for order in self:
            categ_qtys = {}
            for line in order.order_line:
                if line.product_id.categ_id not in categ_qtys:
                    categ_qtys[line.product_id.categ_id] = 0.0
                categ_qtys[line.product_id.categ_id] += line.product_qty
            msgs = []
            for categ, qty in categ_qtys.iteritems():
                if qty < categ.qty_for_discount:
                    msgs.append(msg % (qty, categ.name))
            if msgs:
                order.discount_warning_message = "".join(msgs)
    

    General advice: Always try to debug into your methods. Are they even called? If not, the methods aren't the problem.