在django app中显示出生日期

时间:2014-03-06 00:33:51

标签: python django

如何显示dob获得的年龄?有什么建议吗?

models.py

from django.db import models
import datetime

dob = models.DateField(max_length=8)
age = models.IntegerField() 
def __str__(self):
    today = date.today()
        age = today.year - dob.year
    if today.month < dob.month or today.month == dob.month and today.day < dob.day:
        age -= 1
    return self.age 

谢谢你, 拉德

2 个答案:

答案 0 :(得分:1)

您应该使用python-dateutil在日期之间获取relativedelta

from dateutil.relativedelta import relativedelta
from django.db import models

dob = models.DateField(max_length=8)
age = models.IntegerField() 
def __str__(self):
    today = date.today()
    delta = relativedelta(today, self.dob)
    return str(delta.years)

答案 1 :(得分:0)

根据here计算出生日期,您可以将此功能放在模型上。您不需要将age存储在数据库中。

from datetime import date
from django.db import models


class Person(models.Model):
    dob = models.DateField()

    def calculate_age(self):
        today = date.today()

        try: 
            birthday = self.dob.replace(year=today.year)
        # raised when birth date is February 29 and the current year is not a leap year
        except ValueError:
            birthday = self.dob.replace(year=today.year, day=born.day-1)

        if birthday > today:
            return today.year - born.year - 1
        else:
            return today.year - born.year