具有更好性能的约束
Constraints with better performence
在我的模型中,client_id 每个产品必须一个。所以我想对这种情况做一个约束
class ClientSystemCode(models.Model):
_name = 'client.system.code'
_description = 'Client System Code'
client_id = fields.Many2one('res.partner', 'Client')
product_id = fields.Many2one('product.template', 'Product')
client_sys_code = fields.Char('Client system code')
在 product.template 模型中我的约束看起来像这样。
@api.constrains('client_system_code_ids')
def _client_system_code_constraint(self):
duplicates = []
for line in self.client_system_code_ids:
if line.client_id.id not in duplicates:
duplicates.append(line.client_id.id)
else:
raise ValidationError(_("Product can't have more than one client code with same client"))
没关系,因为它是从产品表单视图触发的,而且总是没有那么多行。但是 client.system.code 中的约束在性能方面应该更好,因为可能有数千行。那么有什么更好的解决办法吗?
您可以使用 sql 约束轻松完成它,例如:
class ClientSystemCode(models.Model):
_name = 'client.system.code'
_sql_constraints = [
('client_product_unique', 'unique (client_id, product_id)', 'Product can't have more than one client code with same client'),
]
在我的模型中,client_id 每个产品必须一个。所以我想对这种情况做一个约束
class ClientSystemCode(models.Model):
_name = 'client.system.code'
_description = 'Client System Code'
client_id = fields.Many2one('res.partner', 'Client')
product_id = fields.Many2one('product.template', 'Product')
client_sys_code = fields.Char('Client system code')
在 product.template 模型中我的约束看起来像这样。
@api.constrains('client_system_code_ids')
def _client_system_code_constraint(self):
duplicates = []
for line in self.client_system_code_ids:
if line.client_id.id not in duplicates:
duplicates.append(line.client_id.id)
else:
raise ValidationError(_("Product can't have more than one client code with same client"))
没关系,因为它是从产品表单视图触发的,而且总是没有那么多行。但是 client.system.code 中的约束在性能方面应该更好,因为可能有数千行。那么有什么更好的解决办法吗?
您可以使用 sql 约束轻松完成它,例如:
class ClientSystemCode(models.Model):
_name = 'client.system.code'
_sql_constraints = [
('client_product_unique', 'unique (client_id, product_id)', 'Product can't have more than one client code with same client'),
]