我有一些代码可以按年龄进行过滤和排序,之前的假设是我们正在查询存储时间的模型作为单个整数.这些是我正在制作的电话类型:
user_profiles = user_profiles.filter(age__gte=min_age, age__lte=max_age)
user_profiles.order_by("age")
Run Code Online (Sandbox Code Playgroud)
作为重构的一部分,我改变了我的模型来存储出生年/月/日而不是静态年龄.我不清楚查询调用应该如何转换为这个问题,但是..如果我想查询14到20岁之间的用户,当你需要结合3个不相交的结果时,如何在Django中完成列?
由于您对重构持开放态度,我强烈建议将生日更改为单个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")
Run Code Online (Sandbox Code Playgroud)
大多数数据库(更不用说Django)都内置了对日期和时间字段的支持,因此在可能的情况下使用它们是有意义的.