This question has been flagged
3 Replies
407 Views

I'm new to odoo, I have 2 date fields, I have tried in various ways to get the calculation taken by a third field, but I can't get it to work when placing it in the view. The code I am using on the calculated field is this

for record in self:
    if record.x_studio_fecha_prevista_1 and record.create_date:
        date_diff = record.x_studio_fecha_prevista_1 - record.create_date
        record.x_studio_calculohora = date_diff.total_seconds() / 3600
    else:
        record.x_studio_calculohora = False
Avatar
Discard

Hi Katalina,

I did test my solution, and when the date is changed it does recalculate the number of days. That's defining the computed field as "stored".

Don't forget to include both fields as dependencies.

Having said that, I have had problems before with computed fields! Maybe someone else can offer more advice!

Best Answer

Hi,

In your compute function code, there appears to be an error, particularly in the computation of the date difference. Let's address the problem in the third field:

Dependencies: x_studio_start_date, x_studio_end_date

Compute:

for record in self:
    date_diff = (record.x_studio_end_date - record.x_studio_start_date).total_seconds() / 3600 if record.x_studio_start_date and record.x_studio_end_date else 0
    record['x_studio_date_difference'] = date_diff

Explanation:

The corrected code snippet calculates the date difference accurately by subtracting the end date from the start date. Additionally, it ensures that the computation only proceeds if both the start date and end date are present. If either of these dates is missing, it sets the date difference to zero.

This adjustment should resolve the error in your compute function code. If you encounter any further issues or have additional questions, feel free to ask for clarification.

Hope it helps

Avatar
Discard
Best Answer

There are many Python experts on here who will know this better than me, but this should work:

for record in self:
    if record.x_studio_fecha_prevista_1 and record.create_date:
        record['x_studio_calculohora'] = (record.x_studio_fecha_prevista_1 - record.create_date).days
    else:
        record['x_studio_calculohora'] = False

Dependencies: x_studio_calculohora, x_studio_fecha_prevista_1


Avatar
Discard
Author Best Answer

Hi, Thank you for you reply, i tried whit both code, but it don't work, an error appears when trying to place the field in the list view in which I am performing the calculation, the operation worked at one point only because the stored option was enabled, but it gave an incorrect data for the same reason, when removing the stored option fails again.


Avatar
Discard