在某些业务场景下,需要通过继承model来修改数据约束。修改主要有三类:
1、增加约束:
增加约束相对比较简单,按下面示例即可:
class FooBar(models.Model):
_name = 'my.foobar'
# ...
_sql_constraints = [
('foo_bar_uniq', 'unique("foo", "bar")', 'You could not step twice into the same foobar!')
]
2、修改约束:
修改约束直接重写一下约束条件即可,例如:
原model:
class UtmTag(models.Model):
"""Model of categories of utm campaigns, i.e. marketing, newsletter, ... """
_name = 'utm.tag'
_description = 'UTM Tag'
_order = 'name'
name = fields.Char(required=True, translate=True)
color = fields.Integer(string='Color Index')
_sql_constraints = [
('name_uniq', 'unique (name)', "Tag name already exists !"),
]
继承model:
class UtmTag(models.Model):
_inherit = 'utm.tag'
_sql_constraints = [
('name_color_uniq', 'unique (name, color)', "Tag name with same color already exists !"),
]
3、取消约束:
无法直接删除约束条件来取消约束,一般是重写约束条件,把CHECK条件改成1=1,如下:
class stock_production_lot(models.Model):
_inherit = "stock.production.lot"
_sql_constraints = [('name_ref_inique', 'check(1=1)', 'No error'),]
4、修改约束顺序:
这种一般是要把继承类中的约束条件放到前面,示例如下:
class Foo(models.Model):
_inherit = 'my.foo'
# ...
# 定义一个新约束
_sql_constraints = [
('name_uniq', 'unique(name)', 'Two foos with the same name? Impossible!')
]
# 重写 _auto_init 反转约束条件顺序
def _auto_init(self):
self._sql_constraints = self._sql_constraints.reverse()
super(Foo, self)._auto_init()
==================
补充:以上方法可能不生效,可参考
https://www.programmersought.com/article/49621062618/
试试