Odoo 8中跨月日期记录按月分组显示的实现需求
Odoo 8 实现跨月记录的按月分组筛选
要让跨月的记录(如2022-04-11至2022-05-12)同时出现在对应月份的分组中,你需要重写模型的read_group方法,自定义分组逻辑,将记录计入所有覆盖的月份分组。
实现步骤
重写
read_group方法
在你的模型中添加以下代码,处理按月分组的核心逻辑:from openerp import models, fields, api from datetime import datetime from dateutil.relativedelta import relativedelta class YourModel(models.Model): _inherit = 'your.model' # 替换为实际模型名 check_in = fields.Date(string='入住日期') check_out = fields.Date(string='退房日期') def _get_covered_months(self): """计算当前记录覆盖的所有年月(格式:YYYY-MM)""" months = [] if not self.check_in or not self.check_out: return months start = datetime.strptime(self.check_in, '%Y-%m-%d') end = datetime.strptime(self.check_out, '%Y-%m-%d') current = start while current <= end: year_month = current.strftime('%Y-%m') if year_month not in months: months.append(year_month) current += relativedelta(months=1) return months @api.model def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True): # 仅处理按月分组的场景(匹配check_in或check_out的月份分组) if groupby and (groupby[0] == 'check_in:month' or groupby[0] == 'check_out:month'): records = self.search(domain) grouped_data = {} for rec in records: # 遍历当前记录覆盖的所有月份 for month in rec._get_covered_months(): key = (month,) if key not in grouped_data: # 初始化分组基础数据 grouped_data[key] = { '__count': 0, 'check_in:month': month, # 若需聚合其他字段,在此初始化(如'amount_total': 0) } # 累加记录数 grouped_data[key]['__count'] += 1 # 若需聚合其他字段,在此添加累加逻辑(如grouped_data[key]['amount_total'] += rec.amount_total) # 按年月排序后返回分组结果 return sorted(grouped_data.values(), key=lambda x: x['check_in:month']) # 其他分组场景调用父类默认方法 return super(YourModel, self).read_group(domain, fields, groupby, offset, limit, orderby, lazy)配置视图分组选项
在模型的搜索视图中添加按月分组的筛选器:<search string="你的模型搜索"> <field name="check_in"/> <field name="check_out"/> <group expand="0" string="分组"> <filter string="按入住月份分组" context="{'group_by': 'check_in:month'}"/> <filter string="按退房月份分组" context="{'group_by': 'check_out:month'}"/> </group> </search>
关键说明
_get_covered_months方法负责计算单条记录覆盖的所有年月,从入住日期当月开始逐月遍历至退房日期当月。- 重写
read_group后,当用户选择按月分组时,跨月记录会被分别计入所有覆盖的月份分组,而非仅归属到单个月份。 - 若需要聚合金额、数量等其他字段,只需在分组初始化和遍历记录时添加对应的累加逻辑即可。
内容的提问来源于stack exchange,提问作者BnsHm
相关产品推荐
相关产品推荐

