当生日以年/月/日字段存储时,如何在Django中从DB查询 [英] How to query from the DB by age in Django when birthday is stored as year/month/day fields

查看:430
本文介绍了当生日以年/月/日字段存储时,如何在Django中从DB查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码可以按年龄进行过滤和排序,以前的假设是我们将存储年龄查询为一个整数。这些是我正在进行的电话类型:

  user_profiles = user_profiles.filter(age__gte = min_age,age__lte = max_age)
user_profiles.order_by(age)

作为重构的一部分,我已经更改了模型用于存储出生年/月/日,而不是静态年龄。我不清楚如何将查询调用解释为这个,但是..如果我想查询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(出生日期)

大多数数据库(更不用说Django)都内置了对日期和时间字段的支持,所以在可能的情况下使用这些是有意义的。


I have some code to filter and sort by age, that previously worked off of the assumption that the model we are querying over stored age as a single integer. These are the types of calls I was making:

user_profiles = user_profiles.filter(age__gte=min_age, age__lte=max_age)
user_profiles.order_by("age")

As part of a refactor, I've changed my model to store the birth year/month/day rather than a static age. It's not clear to me how the querying calls should be translated to account for this, though.. If I want to query users between 14-20 years of age, how is this accomplished in Django when you need to combine the results of 3 disjoint columns?

解决方案

Since you're open to refactoring, I strongly recommend turning the birthdate into a single DateField rather than using three separate columns. Then you can do something like this:

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")

Most databases (not to mention Django) have built-in support for date and time fields, so it makes sense to use those when possible.

这篇关于当生日以年/月/日字段存储时,如何在Django中从DB查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆