跳至内容
菜单
此问题已终结
1 回复
1510 查看

I want to check before creating/editing whether the employee has had a "Sales table" before, the condition is that an employee only has 1 sales table in 1 year.

The problem I'm having is that employee B has never created a Sales table but I get an error message "The {self.year} Sales table has been prepared for {self.employee_id.name} employees"


Here is my code:

class SalesTable(models.Model):
_name = "sales.table"
_description = "Bảng doanh số"
_order = "year"

name = fields.Char(string="Name sales table")
company_id = fields.Many2one(comodel_name="res.company", string="Applies to companies",
default=lambda self: self.env.company)
year = fields.Char(string="Year", default=lambda self: datetime.date.today().year, readonly=True)
employee_id = fields.Many2one(comodel_name="hr.employee")
groups_employee = fields.One2many(comodel_name="group.employee", inverse_name="sales_table_id")
line_ids = fields.One2many(comodel_name="sales.table.line", inverse_name="sales_table_id")
type = fields.Selection(selection=[('single', "Single"), ('group', 'Group')], default='single', string="Type")

@api.constrains("line_ids")
def _check_validate_max_one_line(self):
for r in self:
if len(r.line_ids) > 1:
raise UserError("Doanh số chỉ được 1 dòng")
if len(r.line_ids) == 0:
raise UserError("Doanh số chưa được đặt")

@api.constrains("employee_id")
def _check_validate_employee(self):
for r in self:
sales_tables = self.search(
[('employee_id', '=', r.employee_id.id), ('year', '=', r.year)])
if sales_tables:
raise UserError(f"The {r.year} Sales table has been prepared for {r.employee_id.name} employees")
形象
丢弃
最佳答案

Hi  nganvo,

Try, 

_sql_constraints = [

        (

            'unique_employee_year',

            'UNIQUE(employee_id, year)',

            'An employee can have only one sales table per year!'

        ),

    ]



OR 



@api.constrains("employee_id", "year")

def _check_validate_employee_year(self):

    for rec in self:

        existing_tables = self.search(

            [('employee_id', '=', rec.employee_id.id), ('year', '=', rec.year), ('id', '!=', rec.id)])


        if existing_tables:

            raise UserError(f"Only one Sales table allowed for {rec.employee_id.name} in the year {rec.year}")

Hope it helps,
Kiran K



形象
丢弃
相关帖文 回复 查看 活动
1
5月 23
2224
2
3月 24
1529
1
1月 24
1810
1
7月 25
114
1
5月 25
2125