Skip to Content
Menu
You need to be registered to interact with the community.
This question has been flagged
3 Odgovori
303 Prikazi

I added a constraint on standard_price in my custom module to prevent zero or negative values:

@api.constrains('standard_price') def _check_standard_price(self): price_unit_prec = self.env['decimal.precision'].precision_get('Product Price') for rec in self: if float_compare(rec.standard_price, 0.0, precision_rounding=price_unit_prec) < 1: print("_check_standard_price", rec.standard_price) raise ValidationError(_('Invalid Cost Price.'))

Problem:

Entering 1 triggers a ValidationError, even though it’s positive. My debug prints show:

float_compare rounding_factor 3 value1 0.0 value2 0.0 delta 0.0 float_is_zero epsilon 3 _check_standard_price 1.0

Analysis:

  • price_unit_prec comes from Decimal Accuracy → Product Price (3 in my case).
  • Odoo rounds using float_round(value, rounding_factor), so 1 gets rounded to 0.0 and fails the check.
  • Changing Decimal Accuracy to 2 makes it work correctly (1 → 1.00).
Avatar
Opusti
Best Answer

Hi,

You need to convert precision (digits) into a rounding factor.

Code:

from odoo.tools import float_compare


@api.constrains('standard_price')

def _check_standard_price(self):

    price_unit_prec = self.env['decimal.precision'].precision_get('Product Price')

    rounding = 10 ** (-price_unit_prec)   # convert digits → factor

    for rec in self:

        if float_compare(rec.standard_price, 0.0, precision_rounding=rounding) <= 0:

            raise ValidationError(_('Invalid Cost Price.'))


Hope it helps


Avatar
Opusti
Best Answer

 Hi,

You’re passing the wrong value into float_compare. precision_get('Product Price') returns digits (e.g. 3), but float_compare expects a rounding factor (e.g. 0.001). Convert it with rounding = 10 ** -digits and use that in precision_rounding. That way 1.0 won’t get rounded to 0 and your validation will work correctly.

Avatar
Opusti
Best Answer

Hello Uday, 
I hope this is helpful for you.
Source: Odoo 19

@api.onchange('standard_price')

def _onchange_standard_price(self):

    if self.standard_price < 0:

        raise ValidationError(_("The cost of a product can't be negative."))

Avatar
Opusti
Related Posts Odgovori Prikazi Aktivnost
0
sep. 24
1402
1
jun. 24
1735
1
maj 24
1910
3
maj 24
2138
0
jul. 22
2548