Skip to content

Commit

Permalink
[IMP] sale_margin_percentage: optimize migration script
Browse files Browse the repository at this point in the history
There's a migration script to recompute sales marging on sale order
lines, which was raising memory errors with databases that contain many
lines.

The following optimizations are applied:
- Don't call compute method directly but mark the field to be computed.
  This avoids one write per record and makes the ORM to take care of
  batches.
- Read currency directly from the line, instead of from the pricelist
  which in turn requires reading the order.
- Don't read currency if quantity is zero as it won't be used anyway
  • Loading branch information
luisg123v committed Jul 11, 2024
1 parent b0e79d2 commit 34fc9e8
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@ def update_margin_threshold(env):

def recompute_margin_percent(env):
order_lines = env["sale.order.line"].search([])
order_lines._compute_margin()
env.add_to_compute(field=order_lines._fields["margin_percent"], records=order_lines)
order_lines.flush()
_logger.info("The margin percentage of %s records have been recomputed.", len(order_lines))
2 changes: 1 addition & 1 deletion sale_margin_percentage/models/sale_order_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ class SaleOrderLine(models.Model):
def _compute_margin(self):
res = super()._compute_margin()
for line in self:
currency = line.order_id.pricelist_id.currency_id
if not line.product_uom_qty:
line.margin_percent = 0.0
continue

currency = line.currency_id
if currency.is_zero(line.price_unit) or currency.is_zero(line.price_subtotal):
line.margin_percent = -1.0
continue
Expand Down

0 comments on commit 34fc9e8

Please sign in to comment.