Python django.db.models.DurationField() Examples

The following are 25 code examples for showing how to use django.db.models.DurationField(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.db.models , or try the search function .

Example 1
Project: django-sqlserver   Author: denisenkom   File: tests.py    License: MIT License 6 votes vote down vote up
def test_date_subtraction(self):
        queryset = Experiment.objects.annotate(
            completion_duration=ExpressionWrapper(
                F('completed') - F('assigned'), output_field=models.DurationField()
            )
        )

        at_least_5_days = {e.name for e in queryset.filter(completion_duration__gte=datetime.timedelta(days=5))}
        self.assertEqual(at_least_5_days, {'e3', 'e4', 'e5'})

        at_least_120_days = {e.name for e in queryset.filter(completion_duration__gte=datetime.timedelta(days=120))}
        self.assertEqual(at_least_120_days, {'e5'})

        less_than_5_days = {e.name for e in queryset.filter(completion_duration__lt=datetime.timedelta(days=5))}
        expected = {'e0', 'e2'}
        if connection.features.supports_microsecond_precision:
            expected.add('e1')
        self.assertEqual(less_than_5_days, expected) 
Example 2
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_durationfield_add(self):
        zeros = [e.name for e in Experiment.objects.filter(start=F('start') + F('estimated_time'))]
        self.assertEqual(zeros, ['e0'])

        end_less = [e.name for e in Experiment.objects.filter(end__lt=F('start') + F('estimated_time'))]
        self.assertEqual(end_less, ['e2'])

        delta_math = [
            e.name for e in
            Experiment.objects.filter(end__gte=F('start') + F('estimated_time') + datetime.timedelta(hours=1))
        ]
        self.assertEqual(delta_math, ['e4'])

        queryset = Experiment.objects.annotate(shifted=ExpressionWrapper(
            F('start') + Value(None, output_field=models.DurationField()),
            output_field=models.DateTimeField(),
        ))
        self.assertIsNone(queryset.first().shifted) 
Example 3
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_time_subtraction(self):
        Time.objects.create(time=datetime.time(12, 30, 15, 2345))
        queryset = Time.objects.annotate(
            difference=ExpressionWrapper(
                F('time') - Value(datetime.time(11, 15, 0), output_field=models.TimeField()),
                output_field=models.DurationField(),
            )
        )
        self.assertEqual(
            queryset.get().difference,
            datetime.timedelta(hours=1, minutes=15, seconds=15, microseconds=2345)
        )

        queryset = Time.objects.annotate(difference=ExpressionWrapper(
            F('time') - Value(None, output_field=models.TimeField()),
            output_field=models.DurationField(),
        ))
        self.assertIsNone(queryset.first().difference)

        queryset = Time.objects.annotate(shifted=ExpressionWrapper(
            F('time') - Value(None, output_field=models.DurationField()),
            output_field=models.TimeField(),
        ))
        self.assertIsNone(queryset.first().shifted) 
Example 4
Project: bioforum   Author: reBiocoder   File: functions.py    License: MIT License 5 votes vote down vote up
def __init__(self, expression, *, output_field=None, **extra):
        super().__init__(expression, output_field=output_field or DurationField(), **extra) 
Example 5
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: functions.py    License: MIT License 5 votes vote down vote up
def __init__(self, expression, *, output_field=None, **extra):
        super().__init__(expression, output_field=output_field or DurationField(), **extra) 
Example 6
Project: python   Author: Yeah-Kun   File: functions.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, expression, **extra):
        output_field = extra.pop('output_field', DurationField())
        super(SecondsToInterval, self).__init__(expression, output_field=output_field, **extra) 
Example 7
Project: openhgsenti   Author: drexly   File: functions.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, expression, **extra):
        output_field = extra.pop('output_field', DurationField())
        super(SecondsToInterval, self).__init__(expression, output_field=output_field, **extra) 
Example 8
Project: python2017   Author: bpgc-cte   File: functions.py    License: MIT License 5 votes vote down vote up
def __init__(self, expression, **extra):
        output_field = extra.pop('output_field', DurationField())
        super(SecondsToInterval, self).__init__(expression, output_field=output_field, **extra) 
Example 9
Project: graphene-django   Author: graphql-python   File: test_converter.py    License: MIT License 5 votes vote down vote up
def test_should_auto_convert_duration():
    assert_conversion(models.DurationField, graphene.Float) 
Example 10
Project: django-sqlserver   Author: denisenkom   File: tests.py    License: MIT License 5 votes vote down vote up
def test_time_subtraction(self):
        if connection.features.supports_microsecond_precision:
            time = datetime.time(12, 30, 15, 2345)
            timedelta = datetime.timedelta(hours=1, minutes=15, seconds=15, microseconds=2345)
        else:
            time = datetime.time(12, 30, 15)
            timedelta = datetime.timedelta(hours=1, minutes=15, seconds=15)
        Time.objects.create(time=time)
        queryset = Time.objects.annotate(
            difference=ExpressionWrapper(
                F('time') - Value(datetime.time(11, 15, 0), output_field=models.TimeField()),
                output_field=models.DurationField(),
            )
        )
        self.assertEqual(queryset.get().difference, timedelta) 
Example 11
Project: django-sqlserver   Author: denisenkom   File: tests.py    License: MIT License 5 votes vote down vote up
def test_date_minus_duration(self):
        self.skipTest("TODO fix TypeError: not enough arguments for format string")
        # QUERY = 'SELECT [expressions_experiment].[id], [expressions_experiment].[name], [expressions_experiment].[assigned], [expressions_experiment].[completed], [expressions_experiment].[estimated_time], [expressions_experiment].[start], [expressions_experiment].[end] FROM [expressions_experiment] WHERE [expressions_experiment].[assigned] < ((DATEADD(MICROSECOND, (-1 * (%s %% 1000000)), CAST(DATEADD(SECOND, (%s / 1000000), CAST([expressions_experiment].[completed] as datetime2)) as datetime2)))) ORDER BY [expressions_experiment].[name] ASC' - PARAMS = (345600000000,); args=(345600000000,)
        more_than_4_days = Experiment.objects.filter(
            assigned__lt=F('completed') - Value(datetime.timedelta(days=4), output_field=models.DurationField())
        )
        self.assertQuerysetEqual(more_than_4_days, ['e3', 'e4', 'e5'], lambda e: e.name) 
Example 12
Project: django-sqlserver   Author: denisenkom   File: tests.py    License: MIT License 5 votes vote down vote up
def test_update_duration(self):
        CaseTestModel.objects.update(
            duration=Case(
                # fails on sqlite if output_field is not set explicitly on all
                # Values containing timedeltas
                When(integer=1, then=Value(timedelta(1), output_field=models.DurationField())),
                When(integer=2, then=Value(timedelta(2), output_field=models.DurationField())),
            ),
        )
        self.assertQuerysetEqual(
            CaseTestModel.objects.all().order_by('pk'),
            [(1, timedelta(1)), (2, timedelta(2)), (3, None), (2, timedelta(2)), (3, None), (3, None), (4, None)],
            transform=attrgetter('integer', 'duration')
        ) 
Example 13
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_date_subtraction(self):
        queryset = Experiment.objects.annotate(
            completion_duration=ExpressionWrapper(
                F('completed') - F('assigned'), output_field=models.DurationField()
            )
        )

        at_least_5_days = {e.name for e in queryset.filter(completion_duration__gte=datetime.timedelta(days=5))}
        self.assertEqual(at_least_5_days, {'e3', 'e4', 'e5'})

        at_least_120_days = {e.name for e in queryset.filter(completion_duration__gte=datetime.timedelta(days=120))}
        self.assertEqual(at_least_120_days, {'e5'})

        less_than_5_days = {e.name for e in queryset.filter(completion_duration__lt=datetime.timedelta(days=5))}
        self.assertEqual(less_than_5_days, {'e0', 'e1', 'e2'}) 
Example 14
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_time_subtraction(self):
        Time.objects.create(time=datetime.time(12, 30, 15, 2345))
        queryset = Time.objects.annotate(
            difference=ExpressionWrapper(
                F('time') - Value(datetime.time(11, 15, 0), output_field=models.TimeField()),
                output_field=models.DurationField(),
            )
        )
        self.assertEqual(
            queryset.get().difference,
            datetime.timedelta(hours=1, minutes=15, seconds=15, microseconds=2345)
        ) 
Example 15
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_datetime_subtraction_microseconds(self):
        delta = datetime.timedelta(microseconds=8999999999999999)
        Experiment.objects.update(end=F('start') + delta)
        qs = Experiment.objects.annotate(
            delta=ExpressionWrapper(F('end') - F('start'), output_field=models.DurationField())
        )
        for e in qs:
            self.assertEqual(e.delta, delta) 
Example 16
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_date_minus_duration(self):
        more_than_4_days = Experiment.objects.filter(
            assigned__lt=F('completed') - Value(datetime.timedelta(days=4), output_field=models.DurationField())
        )
        self.assertQuerysetEqual(more_than_4_days, ['e3', 'e4', 'e5'], lambda e: e.name) 
Example 17
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_subtract_temporals(self):
        duration_field = DurationField()
        duration_field_internal_type = duration_field.get_internal_type()
        msg = (
            'This backend does not support %s subtraction.' %
            duration_field_internal_type
        )
        with self.assertRaisesMessage(NotSupportedError, msg):
            self.ops.subtract_temporals(duration_field_internal_type, None, None) 
Example 18
Project: djongo   Author: nesdis   File: test_durationfield.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_formfield(self):
        field = models.DurationField()
        self.assertIsInstance(field.formfield(), forms.DurationField) 
Example 19
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_update_duration(self):
        CaseTestModel.objects.update(
            duration=Case(
                # fails on sqlite if output_field is not set explicitly on all
                # Values containing timedeltas
                When(integer=1, then=Value(timedelta(1), output_field=models.DurationField())),
                When(integer=2, then=Value(timedelta(2), output_field=models.DurationField())),
            ),
        )
        self.assertQuerysetEqual(
            CaseTestModel.objects.all().order_by('pk'),
            [(1, timedelta(1)), (2, timedelta(2)), (3, None), (2, timedelta(2)), (3, None), (3, None), (4, None)],
            transform=attrgetter('integer', 'duration')
        ) 
Example 20
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_date_subtraction(self):
        queryset = Experiment.objects.annotate(
            completion_duration=ExpressionWrapper(
                F('completed') - F('assigned'), output_field=models.DurationField()
            )
        )

        at_least_5_days = {e.name for e in queryset.filter(completion_duration__gte=datetime.timedelta(days=5))}
        self.assertEqual(at_least_5_days, {'e3', 'e4', 'e5'})

        at_least_120_days = {e.name for e in queryset.filter(completion_duration__gte=datetime.timedelta(days=120))}
        self.assertEqual(at_least_120_days, {'e5'})

        less_than_5_days = {e.name for e in queryset.filter(completion_duration__lt=datetime.timedelta(days=5))}
        self.assertEqual(less_than_5_days, {'e0', 'e1', 'e2'})

        queryset = Experiment.objects.annotate(difference=ExpressionWrapper(
            F('completed') - Value(None, output_field=models.DateField()),
            output_field=models.DurationField(),
        ))
        self.assertIsNone(queryset.first().difference)

        queryset = Experiment.objects.annotate(shifted=ExpressionWrapper(
            F('completed') - Value(None, output_field=models.DurationField()),
            output_field=models.DateField(),
        ))
        self.assertIsNone(queryset.first().shifted) 
Example 21
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_datetime_subtraction_microseconds(self):
        delta = datetime.timedelta(microseconds=8999999999999999)
        Experiment.objects.update(end=F('start') + delta)
        qs = Experiment.objects.annotate(
            delta=ExpressionWrapper(F('end') - F('start'), output_field=models.DurationField())
        )
        for e in qs:
            self.assertEqual(e.delta, delta) 
Example 22
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_date_minus_duration(self):
        more_than_4_days = Experiment.objects.filter(
            assigned__lt=F('completed') - Value(datetime.timedelta(days=4), output_field=models.DurationField())
        )
        self.assertQuerysetEqual(more_than_4_days, ['e3', 'e4', 'e5'], lambda e: e.name) 
Example 23
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_subtract_temporals(self):
        duration_field = DurationField()
        duration_field_internal_type = duration_field.get_internal_type()
        msg = (
            'This backend does not support %s subtraction.' %
            duration_field_internal_type
        )
        with self.assertRaisesMessage(NotSupportedError, msg):
            self.ops.subtract_temporals(duration_field_internal_type, None, None) 
Example 24
Project: djongo   Author: nesdis   File: test_durationfield.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_string(self):
        field = models.DurationField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean('not a datetime', None)
        self.assertEqual(cm.exception.code, 'invalid')
        self.assertEqual(
            cm.exception.message % cm.exception.params,
            "'not a datetime' value has an invalid format. "
            "It must be in [DD] [HH:[MM:]]ss[.uuuuuu] format."
        ) 
Example 25
Project: djongo   Author: nesdis   File: test_durationfield.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_formfield(self):
        field = models.DurationField()
        self.assertIsInstance(field.formfield(), forms.DurationField)