我想添加数据库端验证,只允许使用SQL_Constraints或Check约束基于订单ID的一个类别。
表:order_line_table 示例允许仅基于订单ID
插入或更新相同的类别Id Order_id Categ_id
1 1 4
2 1 4
3 1 4
4 2 5
5 2 5
示例不允许根据订单ID插入或更新不同的类别
Id Order_id Categ_id
6 3 4
7 3 5
我尝试了下面的代码,它在服务器端工作。但是使用Web服务xmlrpc验证不起作用。
@api.one
@api.constrains('order_line')
def _check_category(self):
list_categ = []
filter_categ = []
if self.order_line:
order_line_vals = self.order_line
for line_vals in order_line_vals:
for line in line_vals:
categ_id = line.categ_id and line.categ_id.id or False
list_categ.append(line.categ_id.id)
if isinstance(line, dict):
list_categ.append(line['categ_id'])
filter_categ = list(set(list_categ))
if len(filter_categ) > 1:
raise UserError(_('Only one product category is allowed!'))
答案 0 :(得分:1)
起初我误解了你的问题,所以我更新了答案。
为了实现您的目标,您可以在PostgreSQL中使用EXCLUDE
constraint:
CREATE TABLE order_line_table
(
Id SERIAL PRIMARY KEY,
Order_id INT,
Categ_id INT,
EXCLUDE USING GIST
(
Order_id WITH =,
Categ_id WITH <>
)
);
支持GIST
索引<>
运算符have to install an additional PostgreSQL扩展btree_gist
:
CREATE EXTENSION btree_gist;
演示:
# INSERT INTO order_line_table (Order_id, Categ_id) VALUES (1, 2);
INSERT 0 1
# INSERT INTO order_line_table (Order_id, Categ_id) VALUES (1, 2);
INSERT 0 1
# INSERT INTO order_line_table (Order_id, Categ_id) VALUES (1, 3);
ERROR: conflicting key value violates exclusion constraint "orders_order_id_category_id_excl"
DETAIL: Key (Order_id, Categ_id)=(1, 3) conflicts with existing key (Order_id, Categ_id)=(1, 2).