Odoo | 技巧 | 数据校验-更新约束(基于Odoo12)

本文介绍在Odoo12中更新数据库表约束的方法,包括通过覆盖重写和查询删除并新增约束的方式,适用于需要调整唯一性约束的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Odoo12的数据库表约束变化时如何更新约束(_sql_constraints)

两种方式:

  1. 覆盖重写
    举个例子:
    # odoo源码酱紫
    _sql_constraints = [
        ('code_and_name',
         'UNIQUE(code,name)',
         _("Code and Name must be unique!")),
    ]
    
    # 现在变成了 code + company 唯一约束
    # 如果哦我们不介意unique的在数据库中的名称 我们可以酱紫写
    _sql_constraints = [
        ('code_and_name',
         'UNIQUE(code,company_id)',
         _("Code and Company must be unique!")),
    ]
    # 即名称相同,直接覆盖 可以取数据库中查看表的unique选项 
    
    覆盖重写
  2. 查询删除并新增
    	# odoo源码酱紫(account.account)
    	  _sql_constraints = [
            ('code_company_uniq', 
            'unique (code,company_id)', 
            'The code of the account must be unique per company !')
        ]
    	
    	# 查询删除并新增酱紫
    	# -*- coding: utf-8 -*-
    	from odoo import _, api, fields, models, modules
    	from odoo.exceptions import ValidationError
    	import logging
    	_logger = logging.getLogger(__name__)
    
    	class AcountAccountInherit(models.Model):
    	    _inherit = 'account.account'
    	    
    		@api.model_cr
    	    def init(self):
    	        # 删除Odoo源码 科目表的约束条件
    	        cr = self.env.cr
    	        unique_name = 'account_account_code_company_uniq'
    	        table_name = 'account_account'
    	        cr.execute("""SELECT 1 from pg_constraint cs JOIN pg_class cl ON (cs.conrelid = cl.oid)
    	                                           WHERE cs.conname=%s and cl.relname=%s""", (unique_name, table_name))
    	        if cr.fetchone():
    	            cr.execute('ALTER TABLE "%s" DROP CONSTRAINT "%s"' % (table_name, unique_name), )
    	            _logger.info('Dropped CONSTRAINT %s@%s', table_name, unique_name)
    		
    		# 新增新约束
    	    _sql_constraints = [
    	        ('code_and_account_structure',
    	         'UNIQUE(code,account_structure_id)',
    	         _("Code and account structure must be unique!")),
    	    ]
    
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

比特本特

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值