Django ORM按生日分组

时间:2014-06-29 17:45:07

标签: python django postgresql-9.3

我一直在努力寻找一种使用django的ORM在一系列日期中分组的好方法。我有一个用户,有一个生日的字段,我想分组所有10-15岁,15-20岁的用户,等等,并返回组和总数那个年龄段的人。

我的模特:

class Reader(models.Model):
    user = models.OneToOneField(User)
    birth_date = models.DateField()

我的原始sql看起来像这样:

 SELECT count(*) as total,
   CASE
     WHEN EXTRACT(year from AGE(NOW(), birth_date)) <= 10 THEN '1-10'
     WHEN EXTRACT(year from AGE(NOW(), birth_date)) <= 15 THEN '11-15'
     WHEN EXTRACT(year from AGE(NOW(), birth_date)) <= 20 THEN '16-20'
     WHEN EXTRACT(year from AGE(NOW(), birth_date)) <= 25 THEN '21-25'
     WHEN EXTRACT(year from AGE(NOW(), birth_date)) <= 30 THEN '26-30'
     WHEN EXTRACT(year from AGE(NOW(), birth_date)) <= 40 THEN '31-40'
     WHEN EXTRACT(year from AGE(NOW(), birth_date)) <= 50 THEN '41-50'
     WHEN EXTRACT(year from AGE(NOW(), birth_date)) <= 60 THEN '51-60'
     WHEN EXTRACT(year from AGE(NOW(), birth_date)) > 60 THEN '60+'
   END as age
   FROM main_reader AS reader
   GROUP BY age

2 个答案:

答案 0 :(得分:1)

也许对未来的求职者有用。

现在我们可以用Conditional Expressions - Case()When()和聚合函数Count()来解决这个问题:

这里我也使用 relativedelta 来计算日期。

这是一个例子:


from django.utils import timezone
from django.db.models import Count, Case, When
from dateutil.relativedelta import relativedelta


current_date = timezone.now().date()

range_ages = (
    {"lookup": "gte", "label": "-17", "age": [18]},
    {"lookup": "range", "label": "18-24", "age": [18, 25]},
    {"lookup": "range", "label": "25-34", "age": [25, 35]},
    {"lookup": "range", "label": "35-44", "age": [35, 45]},
    {"lookup": "range", "label": "45-54", "age": [45, 55]},
    {"lookup": "range", "label": "55-64", "age": [55, 65]},
    {"lookup": "lt", "label": "65+", "age": [65]},
)

aggr_query = {}
for item in range_ages:
    age = item.get("age")
    lookup = item.get("lookup")
    label = item.get("label")
    # calculate start_date an end_date
    end_date = current_date - relativedelta(years=age[0])
    start_date = current_date - relativedelta(years=age[-1], days=-1)
    f_value = start_date if len(age) == 1 else (start_date, end_date)
    if lookup == "gte":
        aggr_query[label]=Count(Case(When(date_of_birth__gte=f_value, then=1)))
    elif lookup == "lt":
        aggr_query[label]=Count(Case(When(date_of_birth__lt=f_value, then=1)))
    else:
        aggr_query[label]=Count(Case(When(date_of_birth__range=f_value, then=1)))

#Aggregate values
qs_values = MyModel.objects.filter(gender=gender).aggregate(**aggr_query)

输出如下:

{'55-64': 1726, '25-34': 2590, '65+': 5691, '18-24': 517, '45-54': 1209, '-17': 0, '35-44': 2416}

我们也可以使用 annotate() 它返回一个 QuerySet 对象。

答案 1 :(得分:0)

也许尝试这样的事情(未经测试):

case_when_query = "(case when extract...end)" # Your case when query here

extra_qs = Reader.objects.extra(select={'count': 'count(1)', 'age': case_when_query})

query_set = extra_qs.values('count', 'age')
query_set.query.group_by = ['age']