Django ORM how to Round an Avg result

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

    I needed to have both PostgreSQL and SQLite support, but also keep the ability to specify the number of digit to keep.

    Build on previous answers :

    class Round(Func):
        function = 'ROUND'
        arity = 2
        # Only works as the arity is 2
        arg_joiner = '::numeric, '
    
        def as_sqlite(self, compiler, connection, **extra_context):
            return super().as_sqlite(compiler, connection, arg_joiner=", ", **extra_context)
    
    # Then one can use it as:
    # queryset.annotate(avg_val=Round(AVG("val"), 6))
    

    I would have prefered something cleaner like

    if SQLITE:
        arg_joiner=", "
    elif PGSQL:
        arg_joiner = '::numeric, '
    else raise NotImplemented()
    

    but did not find how, feel free to improve !

提交回复
热议问题