How it works...

The read_group() method internally uses the GROUP BY feature of SQL. This makes the read_group method faster, even if you have large datasets. Internally, the Odoo web client uses this method in the charts and the grouped tree view. You can tweak the behavior of the read_group method by using different arguments.

Let's explore the signature of the read_group method:

def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):

The different parameters available for the read_group method are as follows:

  • domain: The domain is used to filter the records. This will be the search criteria for the read_group method.
  • fields: This is a list of the fields to fetch with the grouping. Note that the fields you have mentioned here should be in the groupby parameter, unless you use some aggregate functions. From Odoo version v12, the read_group method supports the SQL aggregate functions. Let's say you want to get the average order amount per customer. In this case, you can use read_group as follows:
self.env['sale.order'].read_group([], ['partner_id', 'amount_total:avg'], ['partner_id'])
  • If you want to access the same field twice but with a different aggregate function, the syntax is a little different. You need to pass the field name as alias:agg(field_name). This example will give you the total and average number of orders per customer:
self.env['sale.order'].read_group([], ['partner_id', 'total:sum(amount_total)', 'avg_total:avg(amount_total)'], ['partner_id'])
Refer to the documentation if you want to learn more about PostgreSQL aggregate functions: https://www.postgresql.org/docs/current/functions-aggregate.html.

The following is a list of the parameters supported by the read_group method:

  • groupby: This parameter will be a list of fields by which the records are grouped. It lets you group records based on multiple fields. To do this, you will need to pass a list of fields. For example, if you want to group the sales orders by customer and order state, you can pass ['partner_id ', 'state'] in this parameter.
  • offset: This parameter is used for pagination. If you want to skip a few records, you can use this parameter.
  • limit: This parameter is used for pagination; it indicates the maximum number of records to fetch.
  • lazy: This parameter accepts Boolean values. By default, its value is True. If this parameter is True, the results are grouped only by the first field in the groupby parameter. You will get the remaining groupby parameters and the domain in the __context and __domain keys in the result. If the value of this parameter is set to False, it will group the data by all fields in the groupby parameter.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset