You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mixins.py 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import sys
  2. from django.db.models.fields import DecimalField, FloatField, IntegerField
  3. from django.db.models.functions import Cast
  4. class FixDecimalInputMixin:
  5. def as_postgresql(self, compiler, connection, **extra_context):
  6. # Cast FloatField to DecimalField as PostgreSQL doesn't support the
  7. # following function signatures:
  8. # - LOG(double, double)
  9. # - MOD(double, double)
  10. output_field = DecimalField(decimal_places=sys.float_info.dig, max_digits=1000)
  11. clone = self.copy()
  12. clone.set_source_expressions([
  13. Cast(expression, output_field) if isinstance(expression.output_field, FloatField)
  14. else expression for expression in self.get_source_expressions()
  15. ])
  16. return clone.as_sql(compiler, connection, **extra_context)
  17. class FixDurationInputMixin:
  18. def as_mysql(self, compiler, connection, **extra_context):
  19. sql, params = super().as_sql(compiler, connection, **extra_context)
  20. if self.output_field.get_internal_type() == 'DurationField':
  21. sql = 'CAST(%s AS SIGNED)' % sql
  22. return sql, params
  23. def as_oracle(self, compiler, connection, **extra_context):
  24. if self.output_field.get_internal_type() == 'DurationField':
  25. expression = self.get_source_expressions()[0]
  26. options = self._get_repr_options()
  27. from django.db.backends.oracle.functions import IntervalToSeconds, SecondsToInterval
  28. return compiler.compile(
  29. SecondsToInterval(self.__class__(IntervalToSeconds(expression), **options))
  30. )
  31. return super().as_sql(compiler, connection, **extra_context)
  32. class NumericOutputFieldMixin:
  33. def _resolve_output_field(self):
  34. source_fields = self.get_source_fields()
  35. if any(isinstance(s, DecimalField) for s in source_fields):
  36. return DecimalField()
  37. if any(isinstance(s, IntegerField) for s in source_fields):
  38. return FloatField()
  39. return super()._resolve_output_field() if source_fields else FloatField()