Django ORM how to Round an Avg result

前端 未结 5 1584
礼貌的吻别
礼貌的吻别 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:47

    Improving on @mrts answer.

    This allows the round function to be parameterised:

    class Round(Func):
      function = 'ROUND'
      arity = 2
    
    Book.objects.all().aggregate(Round(Avg('price'), 2))
    

提交回复
热议问题