diff options
| author | Claude Paroz <claude@2xlibre.net> | 2015-06-05 15:20:37 +0100 |
|---|---|---|
| committer | Tim Graham <timograham@gmail.com> | 2016-03-29 08:14:33 -0400 |
| commit | 03b6947728466e4e907487f30dd4dfec94a8eb2f (patch) | |
| tree | 923a8045ea4b2cc686a072ccbfa1be73f9f5fa06 /django | |
| parent | 53361589905c7c07692cd77f398ce6cb5ac39779 (diff) | |
Fixed #24932 -- Added Cast database function.
Thanks Ian Foote for the initial patch.
Diffstat (limited to 'django')
| -rw-r--r-- | django/db/models/functions.py | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/django/db/models/functions.py b/django/db/models/functions.py index 021535f017..ca73340b85 100644 --- a/django/db/models/functions.py +++ b/django/db/models/functions.py @@ -4,6 +4,39 @@ Classes that represent database functions. from django.db.models import Func, Transform, Value, fields +class Cast(Func): + """ + Coerce an expression to a new field type. + """ + function = 'CAST' + template = '%(function)s(%(expressions)s AS %(db_type)s)' + + mysql_types = { + fields.CharField: 'char', + fields.IntegerField: 'signed integer', + fields.FloatField: 'signed', + } + + def __init__(self, expression, output_field): + super(Cast, self).__init__(expression, output_field=output_field) + + def as_sql(self, compiler, connection, **extra_context): + if 'db_type' not in extra_context: + extra_context['db_type'] = self._output_field.db_type(connection) + return super(Cast, self).as_sql(compiler, connection, **extra_context) + + def as_mysql(self, compiler, connection): + extra_context = {} + output_field_class = type(self._output_field) + if output_field_class in self.mysql_types: + extra_context['db_type'] = self.mysql_types[output_field_class] + return self.as_sql(compiler, connection, **extra_context) + + def as_postgresql(self, compiler, connection): + # CAST would be valid too, but the :: shortcut syntax is more readable. + return self.as_sql(compiler, connection, template='%(expressions)s::%(db_type)s') + + class Coalesce(Func): """ Chooses, from left to right, the first non-null expression and returns it. |
