Django ORM how to Round an Avg result

前端 未结 5 1581
礼貌的吻别
礼貌的吻别 2020-12-10 12:59

I have a model in which I use Django ORM to extract Avg of values from the table. I want to Round that Avg value, how do I do this?

See below I am extracting Avg pri

5条回答
  •  心在旅途
    2020-12-10 13:54

    Building on previous answers, I've come to this solution to make it work for PostgreSQL:

    from django.db.models import Func
    
    class Round2(Func):
        function = "ROUND"
        template = "%(function)s(%(expressions)s::numeric, 2)"
    
    # Then use it as ,e.g.:
    # queryset.annotate(ag_roi=Round2("roi"))
    
    # qs.aggregate(ag_sold_pct=Round2(Sum("sold_uts") / (1.0 * Sum("total_uts"))) * 100
    

提交回复
热议问题