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
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 !