尝试访问class MonthControlRecord(models.Model):
STATUS_CHOICES = (
(0, 'Open'),
(1, 'Locked'),
(2, 'Closed'),
)
employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
first_day_of_month = models.DateField()
status = models.IntegerField(choices=STATUS_CHOICES, default=0)
@property
def get_year_month(self):
return self.first_day_of_month.year, self.first_day_of_month.month
def __str__(self):
return self.employee, self.first_day_of_month
个对象的年和月属性时,我收到错误
属性错误:' str'对象没有属性' date'。
我认为DateField对象被保存为Python Datetime对象而不是字符串。
这是models.py:
employee = Employee.objects.get(staff_number="0001")
mcr = MonthControlRecord(employee=employee, first_day_of_month="2015-12-01")
mcrYearMonth = mcr.get_year_month
和tests.py:
Traceback (most recent call last):
File "/Users/James/Django/MITS/src/timesheet/tests.py", line 87, in test_new_month_control_record
mcrYearMonth = mcr.get_year_month
File "/Users/James/Django/MITS/src/timesheet/models.py", line 54, in get_year_month
return self.first_day_of_month.year, self.first_day_of_month.month
AttributeError: 'str' object has no attribute 'year'
和错误:
{{1}}
答案 0 :(得分:9)
在测试中,您将日期设置为字符串:
mcr = MonthControlRecord(employee=employee, first_day_of_month="2015-12-01")
尝试将其设为日期:
your_date = datetime.date(2015, 12, 1)
mcr = MonthControlRecord(employee=employee, first_day_of_month=your_date)
答案 1 :(得分:0)
此问题的解决方案是在模型上调用full_clean(),这会将字段规范化为DateTime对象。
employee = Employee.objects.get(staff_number="0001")
mcr = MonthControlRecord(employee=employee, first_day_of_month="2015-12-01")
mcr.full_clean()
mcrYearMonth = mcr.get_year_month