约束性能更好

问题描述 投票:1回答:1

在我的模型中,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中的约束应该是更好的性能,因为可能有数千行。那么有什么更好的解决方案吗?

odoo odoo-8 odoo-9
1个回答
2
投票

你可以使用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'),
    ]
© www.soinside.com 2019 - 2024. All rights reserved.