我的模型定义为 -
class ModelName(models.Model):
_name = 'model_name'
student_id = fields.Many2one('op.student', 'Student')
我希望那个学生应该是独一无二的。所以我补充说 -
_sql_constraints = [
('student_unique',
'UNIQUE(student_id)', 'Some message!')
]
但它没有做任何事情。我仍然可以选择同一个学生并保存表格。
我想点击create
按钮时,不应显示已保存记录的学生。
我能做些什么来实现这个目标?
答案 0 :(得分:4)
在您的字段中尝试以下域名功能,我确定您将获得所需的输出。
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