Working with read_group()

There are situations where summarizing or grouping data from the database becomes essential, especially when retrieving statistical or consolidated information. In these cases, the read_group() method is a powerful tool that helps in fetching aggregated data efficiently.

To illustrate this, let’s take an example. Imagine a model named student.student, which is responsible for storing all student-related records.

Student Model

class StudentStudent(models.Model):
    _name = "student.student"
    _description = "Student"

    name = fields.Char(string="Name", required=True)
    category_id = fields.Many2one('student.category', string="Category")
    total_grade = fields.Float(string="Total Grade")

Student Category Model

class StudentCategory(models.Model):
    _name = "student.category"
    _description = "Student Category"
        
    name = fields.Char(string="Name", required=True)
    description = fields.Text(string="Description")

Method Using read_group()

def get_average_cost(self):
    grouped_result = self.read_group(
       [('total_grade', "!=", False)],  # domain
       ['category_id', 'total_grade:avg'],  # fields
       ['category_id']  # group_by
    )
    return grouped_result

Explanation of Parameters

The read_group() method in Odoo is used to retrieve aggregated data, similar to SQL's GROUP BY clause combined with aggregate functions.

  • Domain: Filters records based on conditions. Example: only include students where total_grade is not empty.
  • Fields: Defines which fields to return in the result.
    • field_name: Include a field in the result.
    • field_name:agg: Apply an aggregate function (avg, sum, count).
    • alias:agg(field_name): Assign a custom alias (e.g., average_grade:avg(total_grade)).
  • Group By: Defines how records are grouped. Example: release_date:month groups by month.

Optional Parameters

  • offset: Skip a number of results.
  • limit: Restrict the maximum number of results.
  • orderby: Sort the results.
  • lazy:
    • True (default) → only group by the first field, remaining are lazy-loaded.
    • False → perform all groupings in one query.
whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message