需要条件和转换的计算字段的 Django 查询表达式

Django query expression for calculated fields that require conditions and casting

我正在尝试 运行 一个聚合查询,大致等于:

select 
    sum(impressions) as impressions, 
    sum(clicks) as clicks, 
    sum(clicks)/sum(impressions) as ctr 
from stats 
group by product
order by ctr;

使用的数据库是PostgreSQL。

我做了这个查询表达式(Django 1.9):

Stats.objects.values('product').annotate(
    impressions = models.Sum('impressions'), 
    clicks = models.Sum('clicks'), 
    ctr = models.ExpressionWrapper(
        models.F('clicks')/models.F('impressions')), output_field = models.FloatField()
    )
).order_by('ctr')

它有 2 个问题:

正确的解决方案是什么?

关于如何扩展它的精确数学取决于你,但在嵌套的 ExpressionWrapper 中添加一个 python 常量就足够了:

ctr = models.ExpressionWrapper(
    models.F('clicks')/models.ExpressionWrapper(
        models.F('impressions') + 1, output_field = models.FloatField()
    ),
    output_field = models.FloatField()
)

使用conditional expressions:

from django.db.models import Case, F, Sum, When

Stats.objects.values('product').annotate(
    tot_impressions=Sum('impressions'), 
    tot_clicks=Sum('clicks')
).annotate(
    ctr=Case(When(tot_impressions=0, then=None),  # or other value, e.g. then=0
             # 1.0*... is to get float in SQL
             default=1.0*F('tot_clicks')/F('tot_impressions'),
             output_field=models.FloatField())
).order_by('ctr')

您可以将 django-pg-utils package 用于处理除以零和 returns 浮点值

divide 查询表达式
from pg_utils import divide

Stats.objects.annotate(ctr=divide(F('clicks'), F('impressions')))