Odoo中POS订单商品汇总报表去重及取最大数量问题
Fixing Duplicate Products in POS Product Summary Report
Looks like the issue here is that you're adding an entry to the data list every time you process an order line—even if the product already exists in your summary dictionary. That's why your list length matches the number of order lines and you get duplicates.
Let's adjust the logic to first calculate all the total sales in the dictionary, then build the final data list from that dictionary. Here's the corrected code:
@api.multi def product_summary_test(self): product_summary_dict = {} data = [] if self.date_from and self.date_to: # Search for orders in the specified date range order_detail = self.env['pos.order'].search([ ('date_order', '>=', self.date_from), ('date_order', '<=', self.date_to) ]) if order_detail: # First pass: Calculate total sold quantities for each product for each_order in order_detail: for each_order_line in each_order.lines: product_name = each_order_line.product_id.name if product_name in product_summary_dict: # Add current line's quantity to existing total product_summary_dict[product_name] += each_order_line.qty else: # Initialize the product's total quantity product_summary_dict[product_name] = each_order_line.qty # Second pass: Build the final summary list from the dictionary for product_name, total_qty in product_summary_dict.items(): data.append({ "name": product_name, "sold_qty": total_qty, }) # Test prints to verify results print(len(data)) print(data) # Return consistent type: list (empty if no data, else summary entries) return data if data else []
Key Changes Explained:
- Split logic into two steps: We first loop through all order lines to populate
product_summary_dictwith running totals for each product—no entries are added todataduring this phase. - Build list from aggregated data: After calculating all totals, we iterate over the dictionary to create the final summary entries. This guarantees each product appears exactly once with its total sales.
- Consistent return type: Changed the fallback return from
{}to[]to keep the output type consistent (always a list, either empty or containing summary items).
This approach eliminates duplicates entirely because we're only creating one entry per product, using the summed quantity from the dictionary.
内容的提问来源于stack exchange,提问作者Mohamed Fouad
相关产品推荐
相关产品推荐

