Skip to content

Instantly share code, notes, and snippets.

@balazs-endresz
Created September 26, 2017 14:23
Show Gist options
  • Save balazs-endresz/5a827389beb63e9900ea486ff88c55a1 to your computer and use it in GitHub Desktop.
Save balazs-endresz/5a827389beb63e9900ea486ff88c55a1 to your computer and use it in GitHub Desktop.
cast and round django database functions
from django.db.models import ExpressionWrapper, FloatField, Func
class Cast(Func):
function = 'CAST'
template = '%(function)s(%(expressions)s AS %(db_type)s)'
def __init__(self, expression, db_type):
# convert second positional argument to kwarg to be used in function template
super(Cast, self).__init__(expression, db_type=db_type)
def Round(expr, digits=0, output_field=FloatField()):
# converting to numeric is necessary for postgres
return ExpressionWrapper(Func(Cast(expr, 'numeric'), digits, function='ROUND'), output_field=output_field)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment