Elfadil Sulieman
Elfadil Sulieman

Reputation: 65

using create_date Automatic fields in odoo

I am follow odoo document and in chapter 9 I want to use Automatic field ( create_date) to compute value of another field this is my model.

 _name = "estate.offer"
_description = "this is work as a offer offered to our real estate model"
_log_access = True
price = fields.Float()
status = fields.Selection(selection=[('accepted', 'Accepted'), ('refused', 'Refused')], copy=False)
partner_id = fields.Many2one("res.partner", string="Partner", required=True)
property_id = fields.Many2one("estate.model", 'offer_id', required=True)
validity = fields.Integer(compute="_inverse_date_deadline", inverse="_compute_date_deadline")
date_deadline = fields.Date(string="Date Deadline", compute="_compute_date_deadline",
                            inverse="_inverse_date_deadline")

api.depends('create_date', 'validity')
def _compute_date_deadline(self):
    for record in self:
        record.date_deadline = record.create_date + datetime.timedelta(days=record.validity)

# problem in this function
api.depends('create_date', 'date_deadline')
def _inverse_date_deadline(self):
    #print('f ddd {5} xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxzxxxxxxxxx')
    for record in self:
        record.validity = (record.date_deadline - record.create_date).days

in the odoo document they give this tip:

Tip: the create_date is only filled in when the record is created, therefore you will need a fallback to prevent crashing at time of creation.

Upvotes: 0

Views: 808

Answers (1)

Kenly
Kenly

Reputation: 26678

Odoo will raise the following error when it tries to compute the validity (_inverse_date_deadline):

TypeError: unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime' 

The date_deadline field is of type Date and create_date is of type DateTime.

And the following error when it tries to compute or inverse the date_deadline:

TypeError: unsupported operand type(s) for +: 'bool' and 'datetime.timedelta'

This happens because create_date is not already set.

To fix those issues you can:

  • Change the date_deadline field type or convert its value like folowing:

    fields.Datetime.to_datetime(record.date_deadline)
    
  • Handle the empty date_deadline field value, if it is set, compute validity and if not, provide a default value (You must assign the computed value to the field).

  • Handle the create_date, you can provide a default value when creating:

    record.create_date or fields.Datetime.now()
    

Upvotes: 2

Related Questions