【问题标题】:Group by Month and Gender in Django queryset在 Django 查询集中按月份和性别分组
【发布时间】:2018-12-09 02:40:10
【问题描述】:

我有以下查询集,它适用于按月分组

from django.db.models.functions import TruncMonth

queryset = UserProfile.objects.filter(date_created__year='2018')\
           .annotate(date=TruncMonth('date_created'))\
           .values('date').annotate(total_entries=Count('id'))

我想要的也是按 gender 分组,这里有一个与 gender 字段类似的模型

class UserProfile:
    date_created = models.DateTime(auto_now_add=True)
    gender = models.CharField(max_length=3,choices=[('F',"Female"),('M',"Male")],default='M')

预期结果:

May: 5 users [4(Male), 1(Female)]
June: 20 users [15(Male), 5(Female)]

【问题讨论】:

    标签: django django-queryset django-orm


    【解决方案1】:

    对于django < 2.0,您可以使用Conditional ExpressionsSum() 来注释您想要的值:

    from django.db.models import Sum, Case, When
    from django.db.models.functions import TruncMonth
    
    queryset = UserProfile.objects.filter(date_created__year='2018').annotate(
        date=TruncMonth('date_created'),
    ).values('date').annotate(
        total_entries=Count('id'),
        total_male=Sum(Case(When(gender='M', then=1), default=0, output_field=models.IntegerField())),
        total_female=Sum(Case(When(gender='F', then=1), default=0, output_field=models.IntegerField())),
    )
    

    由于django 2.0,您可以使用Conditional Aggregation

    from django.db.models import Count, Q
    from django.db.models.functions import TruncMonth
    
    queryset = UserProfile.objects.filter(date_created__year='2018').annotate(
            date=TruncMonth('date_created'),
        ).values('date').annotate(
            total_entries=Count('id'),
            total_male=Count('id', filter=Q(gender='M')),
            total_female=Count('id', filter=Q(gender='F')),
    )
    

    【讨论】:

    • 太棒了!您的第二个选项为total_entries, total_male, total_female 显示相同的结果,可能是因为我不使用 django >= 2.0。但第一个效果很好
    猜你喜欢
    • 2014-10-24
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    相关资源
    最近更新 更多