跳至内容
菜单
此问题已终结
4 回复
390 查看

I have defined a field in my script that is _inherint res.partners

lookup_status = fields.Integer(string = "Lookup status",
tracking = True,
readonly = True,
default = 0)

The field is  on the screen, it is internal by my script changed, when changed, the changed value is visible. The write function will not see the changed in the vals. 

def write(self, vals):

if 'ep_lookup_status' in vals:
count = vals['ep_lookup_status']
if count == 0:
raise ValidationError(_('EP Lookup status cannot be 0'))

super().write(vals)

Why is the changed value of lookup_status not in vals, it should be. What to to

形象
丢弃

Is lookup_status and ep_lookup_status meant to be the same? What and how is it even changed?

Thanks for this :)

最佳答案

Hi,

Please refer to the code below:

from odoo import models, fields, api
from odoo.exceptions import ValidationError

class ResPartner(models.Model):
"""
Inherits the res.partner model to add a 'lookup_status' field.

This field is an internal indicator managed by backend processes.
It is set to readonly to prevent manual edits through the UI.

Constraints:
- The field 'lookup_status' must not be zero after any update.
Attempting to set it to 0 will raise a ValidationError.
"""

_inherit = 'res.partner'

lookup_status = fields.Integer(string="Lookup Status", tracking=True,
readonly=True, default=0)

@api.constrains('lookup_status')
def _check_lookup_status(self):
"""
Constraint to ensure that 'lookup_status' is never set to 0.

This method is automatically triggered whenever the 'lookup_status'
field is modified. It raises a ValidationError if the value is set to 0,
enforcing a business rule that prohibits this status value.

Raises:
ValidationError: If 'lookup_status' is equal to 0.
"""
for rec in self:
if rec.lookup_status == 0:
raise ValidationError(_('EP Lookup status cannot be 0'))

@api.constrains checks actual field values on the record after creation/update. It works regardless of whether the field was part of the original vals or changed indirectly.write() logic triggers for explicit values passed in the vals dictionary.


Hope it helps.

形象
丢弃
编写者

Thanks for the answer, but it will not work, it took some time toe generate a slimline version to demonstrate the problem:

import logging

from odoo import api, fields, models
from odoo.addons.bag_ep_api.utils.buffer_manager import BufferManager
from odoo.exceptions import ValidationError

_logger = logging.getLogger(__name__)

# Odoo version 18

class ResPartner(models.Model):
_inherit = 'res.partner'

ep_lookup_status = fields.Integer(
string = "EP Lookup status",
tracking = True,
readonly = True,
default = 0
)

@api.model_create_multi
def create(self, vals_list):
partners = super().create(vals_list)

return partners

def write(self, vals):

# if buffer is not active, this will do nothing, also no message the api.constrains will also not work
# when activate in the _onchange it wil preform exact as expected, workaround
buffer = BufferManager.get(self.env.user.id)
if buffer:
for key in buffer:
if key not in vals:
vals[key] = buffer[key]

result = super().write(vals)
for record in self:

if record.ep_lookup_status == 0:
raise ValidationError('Lookup status cannot be 0')

return result

@api.constrains('ep_lookup_status')
def _check_ep_lookup_status(self):
for rec in self:
if rec.ep_lookup_status == 0:
raise ValidationError('Lookup status cannot be 0')

@api.onchange('zip')
def _onchange_zip(self):

# some other code with channing the ep_lookup_status
# for demo

if self.zip == '2035 VS':
self.ep_lookup_status = 1;
else:
self.ep_lookup_status = 0;

BufferManager.set(self.env.user.id,'ep_lookup_status', self.ep_lookup_status)

return self._handle_onchange_result(
ep_lookup_status = self.ep_lookup_status,
)

@staticmethod
def _handle_onchange_result(warnings = None, model_name = None, data_model = None, ep_lookup_status = None):
# #
result = {}
warnings = {}

# some other to infor the user(s)

# Show a warning message if needed
if warnings:
result['warning'] = {
'title': " -- Warning -- ",
'message': "\n".join(warnings),
}

return result or None

编写者

the indents are gone, sorry

编写者

with the appropriate tabs, indents: </>
import logging

from odoo import api, fields, models
from odoo.addons.bag_ep_api.utils.buffer_manager import BufferManager
from odoo.exceptions import ValidationError

_logger = logging.getLogger(__name__)

# Odoo version 18

class ResPartner(models.Model):
_inherit = 'res.partner'

ep_lookup_status = fields.Integer(
string = "EP Lookup status",
tracking = True,
readonly = True,
default = 0
)

@api.model_create_multi
def create(self, vals_list):
partners = super().create(vals_list)

return partners

def write(self, vals):

# if buffer is not active, this will do nothing, also no message the api.constrains will also not work
# when activate in the _onchange it wil preform exact as expected, workaround
buffer = BufferManager.get(self.env.user.id)
if buffer:
for key in buffer:
if key not in vals:
vals[key] = buffer[key]

result = super().write(vals)
for record in self:

if record.ep_lookup_status == 0:
raise ValidationError('Lookup status cannot be 0')

return result

@api.constrains('ep_lookup_status')
def _check_ep_lookup_status(self):
for rec in self:
if rec.ep_lookup_status == 0:
raise ValidationError('Lookup status cannot be 0')

@api.onchange('zip')
def _onchange_zip(self):

# some other code with channing the ep_lookup_status
# for demo

if self.zip == '2035 VS':
self.ep_lookup_status = 1;
else:
self.ep_lookup_status = 0;

BufferManager.set(self.env.user.id,'ep_lookup_status', self.ep_lookup_status)

return self._handle_onchange_result(
ep_lookup_status = self.ep_lookup_status,
)

@staticmethod
def _handle_onchange_result(warnings = None, model_name = None, data_model = None, ep_lookup_status = None):
# #
result = {}
warnings = {}

# some other to infor the user(s)

# Show a warning message if needed
if warnings:
result['warning'] = {
'title': " -- Warning -- ",
'message': "\n".join(warnings),
}

return result or None

编写者 最佳答案

Yes these are the same, the status is changed in a .py when i fetch some data. The status is displayed correct, according to the current value, but not in the vals. There are only in vals when the user touch the field. So all writes will not recognise when the change by a program. The fields needs deforced to update. Think need to write a work around, with a cache / buffer to updater the vals.


her is a slimline example of the problem, also with the workaround to get it working with an bi=uffer to store the value.

import logging


from odoo import api, fields, models
from odoo.addons.bag_ep_api.utils.buffer_manager import BufferManager
from odoo.exceptions import ValidationError


_logger = logging.getLogger(__name__)


# Odoo version 18

class ResPartner(models.Model):
_inherit = 'res.partner'

ep_lookup_status = fields.Integer(
string = "EP Lookup status",
tracking = True,
readonly = True,
default = 0
)


@api.model_create_multi
def create(self, vals_list):
partners = super().create(vals_list)

return partners


def write(self, vals):

# if buffer is not active, this will do nothing, also no message the api.constrains will also not work
# when activate in the _onchange it wil preform exact as expected, workaround
buffer = BufferManager.get(self.env.user.id)
if buffer:
for key in buffer:
if key not in vals:
vals[key] = buffer[key]

result = super().write(vals)
for record in self:

if record.ep_lookup_status == 0:
raise ValidationError('Lookup status cannot be 0')

return result


@api.constrains('ep_lookup_status')
def _check_ep_lookup_status(self):
for rec in self:
if rec.ep_lookup_status == 0:
raise ValidationError('Lookup status cannot be 0')


@api.onchange('zip')
def _onchange_zip(self):

# some other code with channing the ep_lookup_status
# for demo

if self.zip == '2035 VS':
self.ep_lookup_status = 1;
else:
self.ep_lookup_status = 0;

BufferManager.set(self.env.user.id,'ep_lookup_status', self.ep_lookup_status)

return self._handle_onchange_result(
ep_lookup_status = self.ep_lookup_status,
)


@staticmethod
def _handle_onchange_result(warnings = None, model_name = None, data_model = None, ep_lookup_status = None):
# #
result = {}
warnings = {}

# some other to infor the user(s)

# Show a warning message if needed
if warnings:
result['warning'] = {
'title': " -- Warning -- ",
'message': "\n".join(warnings),
}

return result or None
形象
丢弃

Provide an installable but reduced-to-the-problem example of what you've got right now, including manifest, views, and that ominous 'internal script' that changes stuff, things can be worked out. Currently it's just guess work of what your setup looks like and whether you've even used the correct attribute names (i.e. 'ep_lookup_status' vs 'lookup_status').

最佳答案

Hello RacketRebel,

Try below code : 

def write(self, vals):

    res = super().write(vals)

    for rec in self:

        if rec.lookup_status == 0:

            raise ValidationError(_('EP Lookup status cannot be 0'))

        else:

            rec.update({'lookup_status':rec.lookup_status})

    return res


thanks.

形象
丢弃
最佳答案

Hii,

Why Your Check Fails

Your logic:

It only works if lookup_status is in vals, but:

  • If the field was updated via code, and
  • You're calling record.write({}) or record.write({'other_field': val})

Then lookup_status won’t be in vals, so your check silently skips.


Here is updated code 
Check current field value directly on self

If you want to ensure the value isn’t 0 when any write() happens:

def write(self, vals):

    res = super().write(vals)

   

    for rec in self:

        if rec.lookup_status == 0:

            raise ValidationError(_('EP Lookup status cannot be 0'))

   

    return res

try this 

i hope it is use full

形象
丢弃
编写者

The suggested solution did not seem to work. The status displayed on the screen remains 0, while the stored old value is 3. Since the new value is not present in vals, the update does not occur, and as a result, the raise ValidationError is not triggered.

相关帖文 回复 查看 活动
1
6月 23
3823
1
6月 22
5617
0
3月 15
4111
8
2月 24
14154
3
8月 20
3814