This question has been flagged
2 Replies
8575 Views

Is there a way how to validate on a model level? Let say I have integer field:

comp_min = fields.Integer(string='Min. component item')
comp_max = fields.Integer(string='Max. component item')

How do I set that comp_min have to be greater than 0 and lower than comp_max at the same time?

I know I can set min in template, but it would make sence to define this on model level, other wise I have to add check in template in model on change and possibly other places so I am sure that I do not have mismatched data.

Avatar
Discard
Best Answer

You could do it using a python constraint, like:

@api.model

def _check_comp_min(self):

obj = self[0]

if 0 < obj.comp_min < obj.comp_max:

return True

return False

_constraints = [

(_check_comp_min,'The comp_min field is invalid',['comp_min'])

]

Avatar
Discard

Hi Axel ,you are helping all the beginners and expert by odoo blogs.your answers are perfect and correct .awesome job ...Thanks for all answers quickly .I think you are working as 24/7 time it's marvellous...keep in touch ,Keep it up bye cya

Thanks for your kind words. I appreciate that. Yes, I reviewing closely every question that I could help with my previous experience and try to learn about others errors while solving it and also push me to see code and modules that I never used before. This bring an awesome experience because I'm not dealing only with my daily Odoo situations. Always that the community appreciate my contributions is a good day. Beginners today could be Odoo experts in the future

Author Best Answer

Unfortunately I cant comment on @Axel answer.

According documentation _constraints is deprecated and I shall use constraints decorator, so the right way in odoo 9.x would be something like this?


def _check_comp_min(self):

if 0 < self.comp_min < self.comp_max:

return True

     self.comp_min = None # this is not ideal, as value before modification should be here.

return False


@api.onchange('comp_max', 'comp_min'):

def validation_comp_min(self):

     if not self._check_comp_min():

         return {

            'warning': {

                 'title': 'Error',

                 'message': 'You have entered wrong value for component'

             }

         }

     return True


@api.constrains('comp_max', 'comp_min'):

def validation_comp_max(self):

     validation_result = self._check_comp_min()

     if validation_result != True:

         raise ValidationError('You have entered wrong value for component')

This way I would have just one validation function, but it have to be called twice for onchange (to validate immediatelly) and also on constraint so it is validated when saving. Or is there something similar like Django models have? Seems too much code for simple validation to be executed on change and constraint as well...

Avatar
Discard