Сделайте это изменение:
try:
won_percent = (total_won * 100) / total_cost
except ZeroDivisionError:
won_percent = None
print(won_percent)
Возвращает None
, когда total_cost
равно нулю.
Полный код:
@api.multi
def product_summary(self):
product_summary_dict = {}
data=[]
if self.date_from and self.date_to:
order_detail = self.env['pos.order'].search([('date_order', '>=',self.date_from),
('date_order', '<=', self.date_to)])
if order_detail:
for each_order in order_detail:
for each_order_line in each_order.lines:
if each_order_line.product_id.name in product_summary_dict:
product_qty = product_summary_dict[each_order_line.product_id.name]
product_qty += each_order_line.qty
total_sales = each_order_line.price_unit * product_qty
total_cost = each_order_line.product_id.standard_price*product_qty
total_won = total_sales - total_cost
try:
won_perecnt = (total_won * 100) / total_cost
except ZeroDivisionError:
won_perecnt = None
res1 = {
"name": each_order_line.product_id.name,
"sold_qty": product_qty,
"price_unit": each_order_line.price_unit,
'total_sales': total_sales,
"total_cost": total_cost,
"total_won": total_won,
"won_perecnt": won_perecnt,
}
data.append(res1)
else:
product_qty = each_order_line.qty
total_sales = each_order_line.price_unit * product_qty
total_cost = each_order_line.product_id.standard_price * product_qty
total_won = total_sales - total_cost
try:
won_perecnt = (total_won * 100) / total_cost
except ZeroDivisionError:
won_perecnt = None
res2 = {
"name": each_order_line.product_id.name,
"sold_qty": product_qty,
"price_unit": each_order_line.price_unit,
'total_sales': total_sales,
"total_cost": total_cost,
"total_won": total_won,
"won_perecnt": won_perecnt,
}
data.append(res2)
product_summary_dict[each_order_line.product_id.name] = product_qty;
return data if data else {}