【问题标题】:Average age from birth date in djangodjango中从出生日期算起的平均年龄
【发布时间】: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 是否为空。

标签: django django-aggregation


【解决方案1】:

您需要将 str 更改为日期。所以你可以像这样使用datetime.strptime

from datetime import datetime

datetime_str = '08/12/12'

d = datetime.strptime(datetime_str, '%m/%d/%y')


print(d.year)
>>> 2012

在你的情况下:

@register.filter(name='age')
def age(bday, d=None):
    b = datetime.strptime(datetime_str, '%m/%d/%y')
    if d is None:
        d = datetime.date.today()
    return (d.year - bday.year) - int((d.month, d.day) < (bday.month, bday.day))

当然这取决于你的 str 日期是什么样子的,你需要根据自己的需要调整它

【讨论】:

  • 在 MySql 数据库中,我的birth_date 类似于“1985-01-15”。我试过 bday = datetime.strptime(bday, '%Y-%m-%d')。现在我得到:时间数据“birth_date”与格式“%Y-%m-%d”不匹配。
  • 然后使用d = datetime.strptime(datetime_str, '%Y-%m-%d')
  • 这是我更新的过滤器:@register.filter(name='age') def age(bday, d=None): bday = datetime.strptime(bday, '%Y-%m- %d') 如果 d 为无:d = datetime.date.today() return (d.year - bday.year) - int((d.month, d.day)
  • strptime 必须接收格式为“1985-01-15”的日期,其中 1985 是年、01 月和 15 天。如果您以其他格式传递日期,则会引发此异常。此外,如果月份超出范围,如“1985-14-14”,则会出现同样的异常。确保您在任何地方都有相同格式的日期。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 2010-10-14
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多