如何在Django中根据年龄查询数据库,生日以年/月/日字段存储
我有一些代码是用来根据年龄进行筛选和排序的,之前的假设是我们查询的模型里年龄是以一个整数存储的。以下是我之前使用的调用方式:
user_profiles = user_profiles.filter(age__gte=min_age, age__lte=max_age)
user_profiles.order_by("age")
在一次重构中,我把模型改成存储出生的年、月、日,而不是一个固定的年龄。现在我不太清楚该如何调整查询的调用来适应这个变化。如果我想查询年龄在14到20岁之间的用户,Django里该怎么做呢?因为这需要结合三个不同的列的结果。
1 个回答
7
既然你愿意对代码进行重构,我非常建议把出生日期改成一个单独的 DateField
,而不是用三个不同的列来表示。这样你就可以像下面这样做:
from datetime import date
from django.utils.timezone import now
def age_range(min_age, max_age):
current = now().date()
min_date = date(current.year - min_age, current.month, current.day)
max_date = date(current.year - max_age, current.month, current.day)
return user_profiles.filter(birthdate__gte=max_date,
birthdate__lte=min_date).order_by("birthdate")
大多数数据库(包括Django)都内置了对日期和时间字段的支持,所以在可能的情况下,使用这些字段是很合理的。