From ae1baa7d1d7fcb823e71ce9cb7c17de47ab2ff5e Mon Sep 17 00:00:00 2001 From: Sergey Fedoseev Date: Wed, 27 Dec 2017 22:23:08 +0500 Subject: [PATCH] Refs #28459 -- Improved performance of loading DurationField on SQLite and MySQL. --- django/db/backends/base/operations.py | 5 +---- django/db/models/aggregates.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/django/db/backends/base/operations.py b/django/db/backends/base/operations.py index c9dfee444b..f6d8925278 100644 --- a/django/db/backends/base/operations.py +++ b/django/db/backends/base/operations.py @@ -7,7 +7,6 @@ from django.core.exceptions import ImproperlyConfigured from django.db import NotSupportedError, transaction from django.db.backends import utils from django.utils import timezone -from django.utils.dateparse import parse_duration from django.utils.encoding import force_text @@ -568,9 +567,7 @@ class BaseDatabaseOperations: def convert_durationfield_value(self, value, expression, connection): if value is not None: - value = str(decimal.Decimal(value) / decimal.Decimal(1000000)) - value = parse_duration(value) - return value + return datetime.timedelta(0, 0, value) def check_expression_support(self, expression): """ diff --git a/django/db/models/aggregates.py b/django/db/models/aggregates.py index dbb746b75d..c7284359d4 100644 --- a/django/db/models/aggregates.py +++ b/django/db/models/aggregates.py @@ -94,6 +94,12 @@ class Avg(Aggregate): return FloatField() return super()._resolve_output_field() + def as_mysql(self, compiler, connection): + sql, params = super().as_sql(compiler, connection) + if self.output_field.get_internal_type() == 'DurationField': + sql = 'CAST(%s as SIGNED)' % sql + return sql, params + def as_oracle(self, compiler, connection): if self.output_field.get_internal_type() == 'DurationField': expression = self.get_source_expressions()[0] @@ -153,6 +159,12 @@ class Sum(Aggregate): function = 'SUM' name = 'Sum' + def as_mysql(self, compiler, connection): + sql, params = super().as_sql(compiler, connection) + if self.output_field.get_internal_type() == 'DurationField': + sql = 'CAST(%s as SIGNED)' % sql + return sql, params + def as_oracle(self, compiler, connection): if self.output_field.get_internal_type() == 'DurationField': expression = self.get_source_expressions()[0]