Odoo产品模板成本与售价自动计算逻辑异常求助
Hey there! Let's dig into why your Odoo product margin calculations aren't working as expected. I spot a couple of key issues in your code that are throwing off the results:
1. Incorrect Formula Logic for Margin Percentage
You defined mrg as a percentage value (e.g., 20 for 20% margin), but your calculations aren't converting that percentage to a decimal properly:
- For sales price calculation, you used
1 + self.mrg— this turns a 20% margin into a 21x multiplier instead of the correct 1.2x. - Your cost calculation formula is completely off: the right way to reverse-engineer cost from sales price and margin is
standard_price = list_price / (1 + mrg/100), not(self.mrg * self.list_price) / 100(that calculates gross profit amount, not cost).
2. Conflicting Onchange Functions
You have two separate @api.onchange functions listening to the exact same three fields. This creates unpredictable execution order, leading to calculation results overriding each other.
Fixed Code Implementation
Here's the corrected version with proper logic and merged onchange handling:
from odoo import models, fields, api class Marge_product_template(models.Model): _name = "product.template" _inherit = "product.template" mrg = fields.Integer(string="Marge (in %)") # Added clarity that this is a percentage standard_price = fields.Float(string="Cost", store=True) @api.onchange("list_price", "standard_price", "mrg") def _onchange_margin_calculations(self): # Prevent division by zero if margin is 0 if self.mrg == 0: return # Logic to handle different input scenarios # Scenario 1: User enters cost and margin → auto-calculate sales price if self.standard_price and self.mrg and not self.list_price: self.list_price = self.standard_price * (1 + (self.mrg / 100)) # Scenario 2: User enters sales price and margin → auto-calculate cost elif self.list_price and self.mrg and not self.standard_price: self.standard_price = self.list_price / (1 + (self.mrg / 100)) # Scenario 3: All fields have values → prioritize updating sales price from cost + margin elif self.standard_price and self.mrg: self.list_price = self.standard_price * (1 + (self.mrg / 100))
Key Improvements Explained
- Proper Percentage Conversion: We divide
mrgby 100 to convert the percentage value to a decimal, aligning with your original formulalist_price = standard_price*(1+mrg). - Merged Onchange Logic: A single onchange function eliminates conflicting executions and gives you control over calculation priorities.
- Input Scenario Handling: Clear conditions cover common user workflows (calculating price from cost, or cost from price).
- Error Prevention: Added a check to avoid division by zero when the margin is set to 0.
内容的提问来源于stack exchange,提问作者Dali-Marrag
相关产品推荐
相关产品推荐

