Django query expression for calculated fields that require conditions and casting

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 01:56:07
vsd

Use 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')

The exact math on how you scale this is up to you, but adding in a python constant inside a nested ExpressionWrapper should suffice:

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

You can use the django-pg-utils package for the divide query expression that handles division by zero and returns float values

from pg_utils import divide

Stats.objects.annotate(ctr=divide(F('clicks'), F('impressions')))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!