methods - sql 和 python 约束在 odoo 9 中都不起作用

标签 methods openerp odoo-9

我已经为此苦苦挣扎了一段时间。这两个选项都不起作用,也没有给出错误。我把pythonic constrain方法注释掉给你看。

代码片段:

class house_development(models.Model):
    _name = 'house.development'
    _description = 'Development'
    _inherit = ["mail.thread"]

    name = fields.Char(string="Name", required=True, track_visibility='onchange')
    description = fields.Text(string="Description", track_visibility='onchange')

    # @api.one
    # @api.constrains('name')
    # def _identify_same_name(self):
    #     for record in self:
    #         if record.name in self:
    #             raise exceptions.ValidationError("There is another development/project with the same name: %s" % record.name)

    _sql_constraints = [
        ('name_unique',
         'UNIQUE(name)',
         "There is another development/project with the same name"),
    ] 

最佳答案

应该是这样的

@api.multi
@api.constrains('name')
def _identify_same_name(self):
    for record in self:
        obj = self.search([('name','=ilike',record.name),('id','!=',record.id)])
        if obj:
            raise exceptions.ValidationError("There is another development/project with the same name: %s" % record.name)

您需要搜索相同的名称但不是相同的 id。

对于数据库唯一约束,您可以这样添加。

_sql_constraints = [
    ('name_unique', 'unique(name)', 'There is another development/project with the same name!!!'),
] 

Database constrains will not be added if there are duplicate name in table. Sql constrains will apply only if the rule is not violated by the existing data. I think in your case that's the point with Sql constrains. And make sure for that you need to upgrade module. first check duplicate records in database by firing that query.

Select name, count(*) from table_name 
group by name
having count(*) > 1;

odoo 域中的可用运算符 Click to see more .

关于methods - sql 和 python 约束在 odoo 9 中都不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45235527/

相关文章:

perl - 如何确保我的方法调用在正确的对象上使用正确的方法名称?

open-source - OpenERP 可以换肤吗?

odoo - 在 qweb 报告 odoo 中按日期 ASC 排序

javascript - Odoo javascript onclick 事件

python - Odoo 9 空 TreeView

ruby - 使用 class_eval 创建方法

c - C 方法中有关 Float 和 Int 的错误

python - 如何将 Odoo 中的菜单链接到计算的 URL

xml - 顶部菜单条未显示在 openerp 编辑表单中

ruby - 为什么方法声明在 ruby​​ 中评估为 nil?