odoo中常用功能代码小片段

一、去除字符串的中文、英文

    def remove_letters_and_chinese(self,text):
        """字符串去除字母与中文"""
        import re
        pattern = r'[\u4e00-\u9fa5a-zA-Z]'
        result = re.sub(pattern, '', text)
        return result

二、根据时分来判断是当天还是第二天

    def set_format_datetime(self,type, date1, date2):
        """ 
         str_date1='2023-06-27'
         str_date2='23:30'
        """
        from datetime import datetime, timedelta
        str_date1 = self.remove_letters_and_chinese(date1)
        str_date2 = self.remove_letters_and_chinese(date2)
        if type == 'next':
            dt = datetime.strptime(f"{str_date1} {str_date2}", "%Y-%m-%d %H:%M")
        else:
            ql_house = int(str_date2.split(':')[0])
            if 13 < ql_house < 24:
                date_obj = datetime.strptime(str_date1, '%Y-%m-%d')
                next_day = date_obj - timedelta(days=1)
                dt = datetime.strptime(f"{next_day.strftime('%Y-%m-%d')} {str_date2}", "%Y-%m-%d %H:%M")
            else:
                dt = datetime.strptime(f"{str_date1} {str_date2}", "%Y-%m-%d %H:%M")
        print('=====dt====----------9999---------------===', dt)
        return dt.strftime("%Y-%m-%d %H:%M:%S")

 

三、获取两个时分的时间差

    def get_on_bed_time(self, start_time, end_time):
        from datetime import datetime, timedelta
        # 将时间字符串转换为datetime对象
        start_time = self.remove_letters_and_chinese(start_time)
        end_time = self.remove_letters_and_chinese(end_time)
        dt1 = datetime.strptime(start_time, '%H:%M')
        dt2 = datetime.strptime(end_time, '%H:%M')
        # 如果dt2比dt1大,说明时间跨越了一天,需要将dt2加上一天
        if dt2 < dt1:
            dt2 += timedelta(days=1)
        # 计算时间差
        delta = dt2 - dt1
        # 将时间差转换为小时数
        hours = delta.seconds // 3600
        # # 将时间差转换为分钟数
        minutes = delta.seconds // 60
        print(f"时间差为{hours}小时或{minutes}分钟")
        return delta.seconds

 

四、日期的加减加一天减一天

    def set_report_date(self, date1):
        """获取日期"""
        from datetime import datetime, timedelta
        date_obj = datetime.strptime(date1, '%Y-%m-%d')
        next_day = date_obj - timedelta(days=1)
        return next_day.strftime("%Y-%m-%d")

 

五、获取区间中的日期

    def get_dates_between(self, start_date, end_date):
        """获取区间中的日期"""
        from datetime import datetime, timedelta
        dates = []
        current_date = datetime.strptime(str(start_date), "%Y-%m-%d")
        end_date = datetime.strptime(str(end_date), "%Y-%m-%d")
        while current_date <= end_date:
            dates.append(current_date.strftime("%Y-%m-%d"))
            current_date += timedelta(days=1)
        return dates

 

六、write与create常见的操作

class Job(models.Model):
    _inherit = 'hr.job'

    group_id = fields.Many2one('res.groups', string=u'岗位权限', domain=[('is_job_group', '=', True)])
    job_user_ids = fields.Many2many('res.users', 'zimo_m2m_job_user', string=u'岗位人员')

    @api.model
    def _on_create_job_user_changed(self, job):
        if job.group_id and job.job_user_ids:
            job.group_id.write({'users': [(4, job_user.id) for job_user in job.job_user_ids]})

    @api.model
    def _on_write_job_user_changed(self, job, add_user_list, remove_user_list):
        if job.group_id:
            # 获取当前岗位下已有的用户列表
            # 根据新增的岗位人员将人员添加到权限组中
            added_users = add_user_list
            if added_users:
                job.group_id.write({'users': [(4, user.id) for user in added_users]})
            # 根据删除的岗位人员将人员从权限组中删除
            removed_users = remove_user_list
            if removed_users:
                job.group_id.write({'users': [(3, user.id) for user in removed_users]})

    @api.model_create_multi
    def create(self, vals_list):
        jobs = super(Job, self).create(vals_list)
        for job in jobs:
            group_vals = {
                'name': job.name,
                'category_id': self.env.ref('zimo_increment_base.module_zimo_job_title').id,
                'implied_ids': [(6, 0, [self.env.ref('base.group_user').id])],
                'is_job_group': True,
                'users': [(4, user.id) for user in job.job_user_ids if job.job_user_ids],
            }
            job.group_id = self.env['res.groups'].create(group_vals)
            self._on_create_job_user_changed(job)
        return jobs

    def write(self, vals):
        old_job_user_ids = self.job_user_ids
        res = super(Job, self).write(vals)
        new_job_user_ids = self.job_user_ids
        add_user_list = [i for i in new_job_user_ids if i not in old_job_user_ids]
        remove_user_list = [i for i in old_job_user_ids if i not in new_job_user_ids]
        # 分别做操作
        if 'group_id' in vals or 'job_user_ids' in vals:
            for job in self:
                self._on_write_job_user_changed(job, add_user_list, remove_user_list)
        return res

 

posted @ 2023-06-27 15:26  何双新  阅读(102)  评论(0编辑  收藏  举报