【发布时间】:2023-04-04 22:40:01
【问题描述】:
在我的 django(3.0.5) 应用程序中,我试图从模型中的出生日期获取平均年龄。我正在使用 MySql 数据库。 以下是我的尝试:
型号:
class ShippingStaff(models.Model):
full_name = models.CharField('Full Name', max_length=200)
birth_date = models.DateField('Date of Birth', null=True, blank=True)
客户过滤器:
@register.filter(name='age')
def age(bday, d=None):
if d is None:
d = datetime.date.today()
return (d.year - bday.year) - int((d.month, d.day) < (bday.month, bday.day))
观看次数:
def home(request):
shipping_staff = ShippingStaff.objects.aggregate(staff_count=Count('full_name'),
avg_age=Avg(custom_time.age('birth_date'))
我收到如下错误:
Exception Value:
'str' object has no attribute 'year'
Exception Location: /home/smrashel/jahaji/crewdatabd/templatetags/custom_time.py in age, line 31
which is
return (d.year - bday.year) - int((d.month, d.day) < (bday.month, bday.day))
我该如何解决这个问题? 任何帮助将不胜感激。
【问题讨论】:
-
显然您在尝试访问
.year属性时正在访问一个字符串。 -
@monkut 如何将其设为整数?
-
您的数据库中是否有日期为空的行?也许您还应该在访问其字段之前检查 bday 是否为空。