Skip ke Konten
Menu
Pertanyaan ini telah diberikan tanda
1 Balas
2483 Tampilan

I currently have this code, it works well, except if I am creating a new record set value. 

On that time it raises an exception and than the constraint message.

Is they any way to achieve the goal, with either of the two methods, or sql constraint ?


class ApiPartnerProduct(models.Model):
_name = 'api_partner_product'
_description = "API Product to Partner relationship for Electronic API"
_sql_constraints = [('vendorcode_partnerid_unique', 'UNIQUE (x_partner_id & x_vendor_code)', 'API Vendor & Vendor Product Code combination is duplicated.')]

x_product_tmpl_id = fields.Many2one(comodel_name='product.template', string="Product Code", required="1")
x_partner_id = fields.Many2one(comodel_name='api_connector_core', string="API Vendor", ondelete='cascade',
required="1")
x_vendor_code = fields.Char(string="Vendor Product Code", required="1")
x_last_update = fields.Date(string="Last API Update")

@api.onchange('x_vendor_code')
def _check_vendor_partner_duplicate(self):
history=self._origin.read(['x_vendor_code'])
ids = self.env['api_partner_product'].search(
[('x_vendor_code', '=', self.x_vendor_code), ('x_partner_id', '=', self.x_partner_id.id)])
self.res={}
if len(ids) >= 1:
if len(history) != 0:
self.x_vendor_code=history[0]['x_vendor_code']
self.x_partner_id = history[0]['x_parner_id']
else :
self.x_vendor_code=None
return
self.res = {'warning': {'title': "Duplicated Records",'message': "API Vendor & Vendor Product Code combination is duplicated."}}
return self.res


Avatar
Buang
Jawaban Terbai

Hello Elder,

SQL constraints is the easiest method for prevents to the same record.

Ex. In res.partner model you have to put unique constraints for name and email then you can use like,

_sql_constraints = [
    ('unique_partner_record', 'unique(name, email)', "Error message"),
]

Avatar
Buang