简体   繁体   中英

Django - How to calculate age of 10 years above

I have a Model with the normal:

date_of_birth = models.DateTimeField(blank=True, null=True)

Please help me calculate those that are 10 years and above and display them in html. I need to set it so that as soon as someone turns 10 on todays date it automatically displays them.

Use relativedelta to subtract 10 years from your current time, then use it in your queryset:

from django.utils import timezone 
from dateutil.relativedelta import relativedelta

ten_years_ago_time = timezone.now() - relativedelta(years=10)
result = YourModel.objects.filter(date_of_birth__lt=ten_years_ago_time)

This code should goes to views.py , and nothing to do with models.py

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM