To prevent duplication of the client_order_ref field in the sales order model in Odoo 15, you can use a @api.constrains decorator to add a constraint that checks if the value already exists in the database. If a duplicate value is found, you can raise a ValidationError to prevent the user from proceeding with the sales order creation.
Here's an example code:
python
from odoo import api, fields, models, _
class SaleOrder(models.Model):
_inherit = 'sale.order'
client_order_ref = fields.Char('Client Reference')
# Constraint to prevent duplication of client_order_ref
@api.constrains('client_order_ref')
def check_duplicate_client_order_ref(self):
for order in self:
if order.client_order_ref:
duplicate_order = self.search([('client_order_ref', '=', order.client_order_ref), ('id', '!=', order.id)], limit=1)
if duplicate_order:
raise ValidationError(_('The client reference number already exists in the system. Please enter a unique value.'))
In this code snippet, the SaleOrder model inherits the sale.order model and adds a new client_order_ref field. The @api.constrains decorator is used to define a constraint function that checks for duplicates of the client_order_ref field in the database.
The for loop iterates over each sale.order record and checks if the client_order_ref field is not empty. The search() function is used to search for other sale.order records that have the same client_order_ref value, excluding the current record (order.id). If a duplicate record is found, a ValidationError is raised with a warning message that informs the user that the client reference number already exists in the system.
Once you have added this code to your Odoo 15 instance, the constraint will be automatically applied whenever a new sales order is created or an existing one is updated. If the user tries to save a sales order with a duplicate client_order_ref value, they will be prevented from proceeding and will be shown the warning message you defined in the ValidationError