python - 奥杜 10 : How to know if record is already in database or a new one?

标签 python odoo


我正在计算 x 记录的平均值,但我不想包括最后一个记录(触发操作的记录)。我可以在现有记录或新记录中触发该操作(尚未在数据库)。
这是我的代码:

@api.one
@api.depends('stc')
def _compute_average_gross(self):
    if self.stc:
        base_seniority = 12
        match_seniority = self.seniority.split()
        total_seniority = int(match_seniority[0]) + int(match_seniority[2]) * 12
        if total_seniority < 12:
            base_seniority = total_seniority if total_seniority else 1  # avoid dividing by 0
        # if the hr.payslip is already in db
        if self._origin.id:
            limit = 13
            # could be self.env.cr.execute() 
            sum_sbr = sum(self.search([('employee_id', '=', self.employee_id.id)], order='create_date desc', limit=limit)[1:].mapped('line_ids').filtered(lambda x: x.code == 'SBR').mapped('amount'))
            sum_average_gross = sum(self.search([('employee_id', '=', self.employee_id.id)], order='create_date desc', limit=limit)[1:].mapped('average_gross'))
        else:
            limit = 12
            # could be self.env.cr.execute() 
            sum_sbr = sum(self.search([('employee_id', '=', self.employee_id.id)], order='create_date desc', limit=limit).mapped('line_ids').filtered(lambda x: x.code == 'SBR').mapped('amount'))
            sum_average_gross = sum(self.search([('employee_id', '=', self.employee_id.id)], order='create_date desc', limit=limit).mapped('average_gross'))
        self.average_gross = round((sum_sbr + sum_average_gross) / base_seniority, 2)

这样我就得到了一个错误,表明 self 没有 _origin,我尝试使用 origin 但得到了相同的错误。我也尝试过 self.context['params'].get('id') 但它没有按预期工作。
你能帮我吗?

最佳答案

要检查记录是否未保存在数据库中,请执行以下操作:

if isinstance(self.id, models.NewId): 
    # record is not saved in database.
    # do your logic

# record is saved in databse
if not isinstance(self.id, models.NewId):
    # .... 

关于python - 奥杜 10 : How to know if record is already in database or a new one?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60024530/

相关文章:

python - OpenCV 示例错误 - TypeError : 'NoneType' object is not subscriptable

python - 如何在 Python、Odoo 中附加对象和字典值?

javascript - 如何覆盖 Odoo 15 中添加到 core.action_registry 的 JS 函数?

python - 使用 Django REST API 访问 Odoo 数据

python - 在python中将文件路径存储为变量

python - Pandas.read_csv "unexpected end of data"错误

python - 我怎样才能让这个简单的Python登录程序循环起来?

python - 在 `pip` 期间使用 `docker build` 安装 python 模块失败

python - 如何在 Odoo 8 中包含 View

python - Odoo 版本 8 中带有 qweb 模板的报告