-
-
Save balazs-endresz/5a827389beb63e9900ea486ff88c55a1 to your computer and use it in GitHub Desktop.
cast and round django database functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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