Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use a computed field as a field for grouping?

Tags:

odoo

odoo-15

my field

SCHEDULE_SELECTION = [
    ("no_schedule", "Без терміну"),
    ("overdue", "Протерміновано"),
    ("today", "Сьогодні"),
    ("this_week", "Цього тижня"),
    ("next_week", "Наступного тижня"),
    ("after_2_week", "Більше 2 тижнів"),
]
schedule_selection = fields.Selection(selection=SCHEDULE_SELECTION, string="Групування по терміну", compute='_compute_schedule_date')

def _compute_schedule_date(self):
    for i in self:
        
        ...

        if not i.schedule_date or i.done:
            i.schedule_selection = "no_schedule"
        elif i.is_overdue:
            i.schedule_selection = "overdue"
        else:
            selection_difference = (i.schedule_date - now).days
            if i.schedule_date.date() == now_date:
                i.schedule_selection = "today"
            elif selection_difference <= 7:
                i.schedule_selection = "this_week"
            elif selection_difference <= 14:
                i.schedule_selection = "next_week"
            else:
                i.schedule_selection = "after_2_week"   

and search:

<!-- this don`t work, i receive an error -->
<filter string='Термін' name='schedule_selection' domain="[]" context="{'group_by': 'schedule_selection'}"/>

as you can see, in this situation i can`t use "store=True", because this field depends by other fields(stored and computed) and current datetime.

on the Internet I found several posts where people say that for this you need to override the search() method, but I did not find specific examples.

like image 653
Wald Sin Avatar asked Sep 16 '25 05:09

Wald Sin


1 Answers

For that you need the field to be stored in the database.
schedule_selection = fields.Selection(selection=SCHEDULE_SELECTION, string="Групування по терміну", compute='_compute_schedule_date', store=True)

Now Odoo can use the database grouping function. But Odoo does not know when to recalculate the schedule_selection field.
For this usually, there is @api.depends()

@api.depends("done", "schedule_date")
def _compute_schedule_date(self):
    for i in self:

This makes Odoo recalculate the field when done or schedule_date changes.

But you are also using now and that means you have to recalculate all the records every day. For that, you should make daily Scheduled Action that calls _compute_schedule_date on all the records that have the done field False.

like image 50
Paxmees Avatar answered Sep 19 '25 15:09

Paxmees