_sql_constraints 不适用于 Odoo v10
_sql_constraints not working in Odoo v10
我有一个定义为-
的模型
class ModelName(models.Model):
_name = 'model_name'
student_id = fields.Many2one('op.student', 'Student')
我希望那个学生应该是独一无二的。所以我添加了 -
_sql_constraints = [
('student_unique',
'UNIQUE(student_id)', 'Some message!')
]
但它什么也没做。我仍然可以 select 同一个学生并保存表格。
我希望当我点击create
按钮时,不应该显示已保存记录的学生。
我该怎么做才能实现这一目标?
在你的领域尝试下面的域函数,我相信你会得到你需要的输出。
student_id = fields.Many2one('op.student',domain=lambda self: self.get_not_existing_student_id(), string='Student')
@api.model
def get_not_existing_student_id(self):
self.env.cr.execute("select id from op_student where id not in (select student_id from model_name)")
datas = self.env.cr.fetchall()
student_ids = []
for record in datas:
student_ids.append(record[0])
return [('id','in',student_ids)]
其他方式:
student_id = fields.Many2one('op.student',string='Student')
将它放在这样的视图中:
<field name="student_id" context="{'find_existed':1}" options="{'no_create':1}"/>
然后像这样继承op.student模型中的方法name_get()
class op_student(models.Model):
_inherit ="op.student"
@api.multi
def name_get(self):
if self._context.get("find_existed",False):
self.env.cr.execute("select id from op_student where id not in (select student_id from model_name)")
datas = self.env.cr.fetchall()
student_ids = []
for record in datas:
student_ids.append(record[0])
for student in self:
if student in student_ids:
res.append((student.id,student.name))
else:
res=super(op_student,self).name_get()
return res
我有一个定义为-
的模型class ModelName(models.Model):
_name = 'model_name'
student_id = fields.Many2one('op.student', 'Student')
我希望那个学生应该是独一无二的。所以我添加了 -
_sql_constraints = [
('student_unique',
'UNIQUE(student_id)', 'Some message!')
]
但它什么也没做。我仍然可以 select 同一个学生并保存表格。
我希望当我点击create
按钮时,不应该显示已保存记录的学生。
我该怎么做才能实现这一目标?
在你的领域尝试下面的域函数,我相信你会得到你需要的输出。
student_id = fields.Many2one('op.student',domain=lambda self: self.get_not_existing_student_id(), string='Student')
@api.model
def get_not_existing_student_id(self):
self.env.cr.execute("select id from op_student where id not in (select student_id from model_name)")
datas = self.env.cr.fetchall()
student_ids = []
for record in datas:
student_ids.append(record[0])
return [('id','in',student_ids)]
其他方式:
student_id = fields.Many2one('op.student',string='Student')
将它放在这样的视图中:
<field name="student_id" context="{'find_existed':1}" options="{'no_create':1}"/>
然后像这样继承op.student模型中的方法name_get()
class op_student(models.Model):
_inherit ="op.student"
@api.multi
def name_get(self):
if self._context.get("find_existed",False):
self.env.cr.execute("select id from op_student where id not in (select student_id from model_name)")
datas = self.env.cr.fetchall()
student_ids = []
for record in datas:
student_ids.append(record[0])
for student in self:
if student in student_ids:
res.append((student.id,student.name))
else:
res=super(op_student,self).name_get()
return res