Bỏ qua để đến Nội dung
Menu
Câu hỏi này đã bị gắn cờ
1 Trả lời
17058 Lượt xem

My requirement is 

hire_date = fields.Date; 

calculate_start = fields.Date;

If hire_date  is after calculate_start ,the date of calculate_start should be equal hire_date

hr_employee_base.py

from odoo.tools import format_time
from datetime import date, datetime, timedelta, time
from time import time
import datetime
import time
import calendar

##### the hire_date;resign_date;calcucate_start  must be fields.Date

hire_date = fields.Date(string="Hire Date")

calculate_start = fields.Date(string="Start Date", store=True, compute='_get_calculate_date')


@api.onchange('hire_date')
def _get_calcuate_date(self):
    firstday = datetime.datetime.strptime(self.hire_date, "%Y-%m-%d")
    secondday = datetime.datetime.strptime(self.calculate_start, "%Y-%m-%d")
    if firstday > secondday:
          self.calculate_start = self.hire_date

File "/opt/bitnami/apps/odoo/lib/odoo-13.0.post20191110-py3.7.egg/odoo/addons/hr/models/hr_employee_base.py", line 110, in _get_calcuate_date
    firstday = datetime.datetime.strptime(self.hire_date, "%Y-%m-%d")
TypeError: strptime() argument 1 must be str, not datetime.date

Ảnh đại diện
Huỷ bỏ

To avoid the type error re-write the following lines as below

firstday = datetime.datetime.strptime(str(self.hire_date), "%Y-%m-%d")

secondday = datetime.datetime.strptime(str(self.calculate_start), "%Y-%m-%d")

Câu trả lời hay nhất

You don't need to convert the date into the datetime again as Odoo returns the date in datetime.date format, so you don't need to convert it again.

Just try this:

if self.hire_date > self.calculate_start:
    self.calculate_start = self.hire_date ​   ​    ​   ​     ​   ​    ​   ​

In previous versions, Odoo used to returns the date into the string format, so you had to convert it into datetime.

Ảnh đại diện
Huỷ bỏ
Tác giả

Thank you for your answer,but actually I tried it at first and display the below error

File "/opt/bitnami/apps/odoo/lib/odoo-13.0.post20191110-py3.7.egg/odoo/addons/hr/models/hr_employee_base.py", line 110, in _get_calculate_date

if self.hire_date > self.calculate_start:

TypeError: '>' not supported between instances of 'datetime.datetime' and 'bool'

You have to make sure both the fields have value selected. Add following code:

if (if self.hire_date and

self.calculate_start:) and self.hire_date > self.calculate_start:

This condition will make sure if both the fields have value, then compare it.

Tác giả

Thank you very much,it works now.If you dont mind,one more question please,how to set the specific date like "2022-12-31" as default,not the default date as today?

You can either pass the date string in the default or pass the date in the time.strftime function

1: default="'2022-12-31'"

2: default="time.strftime('2022-12-31')"

Bài viết liên quan Trả lời Lượt xem Hoạt động
3
thg 6 25
798
1
thg 1 25
17745
1
thg 1 20
3744
1
thg 12 19
6141
3
thg 4 18
5038