Python django.db.models.TimeField() Examples

The following are 30 code examples of django.db.models.TimeField(). 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 also want to check out all available functions/classes of the module django.db.models , or try the search function .
Example #1
Source File: utils.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def display_for_field(value, field):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon
    from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return smart_text(value) 
Example #2
Source File: utils.py    From bioforum with MIT License 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, (models.BooleanField, models.NullBooleanField)):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display) 
Example #3
Source File: simpletags.py    From ishare with MIT License 6 votes vote down vote up
def load_dates(context):
    data = {}
    cl = context.get('cl')
    if cl.has_filters:
        for spec in cl.filter_specs:
            # 自定义的filter,没有field
            if not hasattr(spec, 'field'):
                continue

            field = spec.field
            field_type = None
            if isinstance(field, models.DateTimeField):
                field_type = 'datetime'
            elif isinstance(field, models.DateField):
                field_type = 'date'
            elif isinstance(field, models.TimeField):
                field_type = 'time'

            if field_type:
                data[spec.field_path] = field_type
    context['date_field'] = data

    return '<script type="text/javascript">var searchDates={}</script>'.format(json.dumps(data, cls=LazyEncoder)) 
Example #4
Source File: utils.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # BooleanField needs special-case null-handling, so it comes before the
    # general null test.
    elif isinstance(field, models.BooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display) 
Example #5
Source File: utils.py    From python with Apache License 2.0 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display) 
Example #6
Source File: utils.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if field.flatchoices:
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return smart_text(value) 
Example #7
Source File: util.py    From Mxonline3 with Apache License 2.0 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.remote_field, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value) 
Example #8
Source File: utils.py    From python2017 with MIT License 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display) 
Example #9
Source File: util.py    From imoocc with GNU General Public License v2.0 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value) 
Example #10
Source File: util.py    From devops with MIT License 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return smart_text(value) 
Example #11
Source File: tests.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_nested_subquery_outer_ref_2(self):
        if django.VERSION < (1, 11, 0):
            self.skipTest("does not work on older django")
        first = Time.objects.create(time='09:00')
        second = Time.objects.create(time='17:00')
        third = Time.objects.create(time='21:00')
        SimulationRun.objects.bulk_create([
            SimulationRun(start=first, end=second, midpoint='12:00'),
            SimulationRun(start=first, end=third, midpoint='15:00'),
            SimulationRun(start=second, end=first, midpoint='00:00'),
        ])
        inner = Time.objects.filter(time=OuterRef(OuterRef('time')), pk=OuterRef('start')).values('time')
        middle = SimulationRun.objects.annotate(other=Subquery(inner)).values('other')[:1]
        outer = Time.objects.annotate(other=Subquery(middle, output_field=models.TimeField()))
        # This is a contrived example. It exercises the double OuterRef form.
        self.assertCountEqual(outer, [first, second, third]) 
Example #12
Source File: tests.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_time_field(self):
        field = models.TimeField()
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(path, "django.db.models.TimeField")
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {})

        field = models.TimeField(auto_now=True)
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {'auto_now': True})

        field = models.TimeField(auto_now_add=True)
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {'auto_now_add': True}) 
Example #13
Source File: test_datetime.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_trunc_date_func(self):
        start_datetime = microsecond_support(datetime(2015, 6, 15, 14, 30, 50, 321))
        end_datetime = microsecond_support(datetime(2016, 6, 15, 14, 10, 50, 123))
        if settings.USE_TZ:
            start_datetime = timezone.make_aware(start_datetime, is_dst=False)
            end_datetime = timezone.make_aware(end_datetime, is_dst=False)
        self.create_model(start_datetime, end_datetime)
        self.create_model(end_datetime, start_datetime)
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=TruncDate('start_datetime')).order_by('start_datetime'),
            [
                (start_datetime, start_datetime.date()),
                (end_datetime, end_datetime.date()),
            ],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertEqual(DTModel.objects.filter(start_datetime__date=TruncDate('start_datetime')).count(), 2)

        with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateField"):
            list(DTModel.objects.annotate(truncated=TruncDate('start_time')))

        with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateField"):
            list(DTModel.objects.annotate(truncated=TruncDate('start_time', output_field=TimeField()))) 
Example #14
Source File: test_datetime.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_trunc_time_func(self):
        start_datetime = microsecond_support(datetime(2015, 6, 15, 14, 30, 50, 321))
        end_datetime = microsecond_support(datetime(2016, 6, 15, 14, 10, 50, 123))
        if settings.USE_TZ:
            start_datetime = timezone.make_aware(start_datetime, is_dst=False)
            end_datetime = timezone.make_aware(end_datetime, is_dst=False)
        self.create_model(start_datetime, end_datetime)
        self.create_model(end_datetime, start_datetime)
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=TruncTime('start_datetime')).order_by('start_datetime'),
            [
                (start_datetime, start_datetime.time()),
                (end_datetime, end_datetime.time()),
            ],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertEqual(DTModel.objects.filter(start_datetime__time=TruncTime('start_datetime')).count(), 2)

        with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to TimeField"):
            list(DTModel.objects.annotate(truncated=TruncTime('start_date')))

        with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to TimeField"):
            list(DTModel.objects.annotate(truncated=TruncTime('start_date', output_field=DateField()))) 
Example #15
Source File: test_datetime.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_trunc_day_func(self):
        start_datetime = microsecond_support(datetime(2015, 6, 15, 14, 30, 50, 321))
        end_datetime = truncate_to(microsecond_support(datetime(2016, 6, 15, 14, 10, 50, 123)), 'day')
        if settings.USE_TZ:
            start_datetime = timezone.make_aware(start_datetime, is_dst=False)
            end_datetime = timezone.make_aware(end_datetime, is_dst=False)
        self.create_model(start_datetime, end_datetime)
        self.create_model(end_datetime, start_datetime)
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=TruncDay('start_datetime')).order_by('start_datetime'),
            [
                (start_datetime, truncate_to(start_datetime, 'day')),
                (end_datetime, truncate_to(end_datetime, 'day')),
            ],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertEqual(DTModel.objects.filter(start_datetime=TruncDay('start_datetime')).count(), 1)

        with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"):
            list(DTModel.objects.annotate(truncated=TruncDay('start_time')))

        with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"):
            list(DTModel.objects.annotate(truncated=TruncDay('start_time', output_field=TimeField()))) 
Example #16
Source File: util.py    From online with GNU Affero General Public License v3.0 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.remote_field, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value) 
Example #17
Source File: util.py    From Dailyfresh-B2C with Apache License 2.0 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.remote_field, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value) 
Example #18
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_time_field(self):
        field = models.TimeField()
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(path, "django.db.models.TimeField")
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {})

        field = models.TimeField(auto_now=True)
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {'auto_now': True})

        field = models.TimeField(auto_now_add=True)
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {'auto_now_add': True}) 
Example #19
Source File: test_datetime.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_trunc_week_func(self):
        start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
        end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), 'week')
        if settings.USE_TZ:
            start_datetime = timezone.make_aware(start_datetime, is_dst=False)
            end_datetime = timezone.make_aware(end_datetime, is_dst=False)
        self.create_model(start_datetime, end_datetime)
        self.create_model(end_datetime, start_datetime)
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=TruncWeek('start_datetime')).order_by('start_datetime'),
            [
                (start_datetime, truncate_to(start_datetime, 'week')),
                (end_datetime, truncate_to(end_datetime, 'week')),
            ],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertEqual(DTModel.objects.filter(start_datetime=TruncWeek('start_datetime')).count(), 1)

        with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"):
            list(DTModel.objects.annotate(truncated=TruncWeek('start_time')))

        with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"):
            list(DTModel.objects.annotate(truncated=TruncWeek('start_time', output_field=TimeField()))) 
Example #20
Source File: test_datetime.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_trunc_date_func(self):
        start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
        end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
        if settings.USE_TZ:
            start_datetime = timezone.make_aware(start_datetime, is_dst=False)
            end_datetime = timezone.make_aware(end_datetime, is_dst=False)
        self.create_model(start_datetime, end_datetime)
        self.create_model(end_datetime, start_datetime)
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=TruncDate('start_datetime')).order_by('start_datetime'),
            [
                (start_datetime, start_datetime.date()),
                (end_datetime, end_datetime.date()),
            ],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertEqual(DTModel.objects.filter(start_datetime__date=TruncDate('start_datetime')).count(), 2)

        with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateField"):
            list(DTModel.objects.annotate(truncated=TruncDate('start_time')))

        with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateField"):
            list(DTModel.objects.annotate(truncated=TruncDate('start_time', output_field=TimeField()))) 
Example #21
Source File: test_datetime.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_trunc_time_func(self):
        start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
        end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
        if settings.USE_TZ:
            start_datetime = timezone.make_aware(start_datetime, is_dst=False)
            end_datetime = timezone.make_aware(end_datetime, is_dst=False)
        self.create_model(start_datetime, end_datetime)
        self.create_model(end_datetime, start_datetime)
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=TruncTime('start_datetime')).order_by('start_datetime'),
            [
                (start_datetime, start_datetime.time()),
                (end_datetime, end_datetime.time()),
            ],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertEqual(DTModel.objects.filter(start_datetime__time=TruncTime('start_datetime')).count(), 2)

        with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to TimeField"):
            list(DTModel.objects.annotate(truncated=TruncTime('start_date')))

        with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to TimeField"):
            list(DTModel.objects.annotate(truncated=TruncTime('start_date', output_field=DateField()))) 
Example #22
Source File: test_datetime.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_trunc_day_func(self):
        start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
        end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), 'day')
        if settings.USE_TZ:
            start_datetime = timezone.make_aware(start_datetime, is_dst=False)
            end_datetime = timezone.make_aware(end_datetime, is_dst=False)
        self.create_model(start_datetime, end_datetime)
        self.create_model(end_datetime, start_datetime)
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=TruncDay('start_datetime')).order_by('start_datetime'),
            [
                (start_datetime, truncate_to(start_datetime, 'day')),
                (end_datetime, truncate_to(end_datetime, 'day')),
            ],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertEqual(DTModel.objects.filter(start_datetime=TruncDay('start_datetime')).count(), 1)

        with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"):
            list(DTModel.objects.annotate(truncated=TruncDay('start_time')))

        with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"):
            list(DTModel.objects.annotate(truncated=TruncDay('start_time', output_field=TimeField()))) 
Example #23
Source File: tests.py    From djongo with 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 #24
Source File: util.py    From StormOnline with Apache License 2.0 5 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value) 
Example #25
Source File: utils.py    From django-idcops with Apache License 2.0 5 votes vote down vote up
def display_for_field(value, field, html=True, only_date=True):
    if getattr(field, 'flatchoices', None):
        if html and field.name == 'color' and value:
            return make_color_icon(value)
        return dict(field.flatchoices).get(value, '')
    elif html and (isinstance(field, (models.BooleanField, models.NullBooleanField))):
        return make_boolean_icon(value)
    elif isinstance(field, (models.BooleanField, models.NullBooleanField)):
        boolchoice = {False: "否", True: "是"}
        return boolchoice.get(value)
    elif value is None:
        return ""
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.ForeignKey) and value:
        rel_obj = field.related_model.objects.get(pk=value)
        if html and COLOR_FK_FIELD and isinstance(rel_obj, Option):
            text_color = rel_obj.color
            if not text_color:
                text_color = 'text-info'
            safe_value = format_html(
                '<span class="text-{}">{}</span>', text_color, rel_obj.text)
            return safe_value
        return force_text(rel_obj)
    elif isinstance(field, models.TextField) and value:
        return force_text(value)
    elif isinstance(field, models.DateTimeField):
        if only_date:
            return formats.date_format(value)
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value) 
Example #26
Source File: pyyaml.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def handle_field(self, obj, field):
        # A nasty special case: base YAML doesn't support serialization of time
        # types (as opposed to dates or datetimes, which it does support). Since
        # we want to use the "safe" serializer for better interoperability, we
        # need to do something with those pesky times. Converting 'em to strings
        # isn't perfect, but it's better than a "!!python/time" type which would
        # halt deserialization under any other language.
        if isinstance(field, models.TimeField) and getattr(obj, field.name) is not None:
            self._current[field.name] = str(getattr(obj, field.name))
        else:
            super(Serializer, self).handle_field(obj, field) 
Example #27
Source File: patches.py    From django-more with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _generate_added_field(self, app_label, model_name, field_name):
        field = self.new_apps.get_model(app_label, model_name)._meta.get_field(field_name)
        # You can't just add NOT NULL fields with no default or fields
        # which don't allow empty strings as default.
        # CHANGED
        # < # Fields that are foreignkeys/m2ms depend on stuff
        # < dependencies = []
        # < if field.remote_field and field.remote_field.model:
        # <     dependencies.extend(self._get_dependencies_for_foreign_key(field))
        # XXX
        preserve_default = True
        time_fields = (models.DateField, models.DateTimeField, models.TimeField)
        if (not field.null and not field.has_default() and
                not field.many_to_many and
                not (field.blank and field.empty_strings_allowed) and
                not (isinstance(field, time_fields) and field.auto_now)):
            field = field.clone()
            if isinstance(field, time_fields) and field.auto_now_add:
                field.default = self.questioner.ask_auto_now_add_addition(field_name, model_name)
            else:
                field.default = self.questioner.ask_not_null_addition(field_name, model_name)
            preserve_default = False
        self.add_operation(
            app_label,
            operations.AddField(
                model_name=model_name,
                name=field_name,
                field=field,
                preserve_default=preserve_default,
            ),
            # CHANGED
            # < preserve_default=preserve_default,
            dependencies=field.dependencies,
            # XXX
        )

    # Replace dependencies logic 
Example #28
Source File: autodetector.py    From bioforum with MIT License 5 votes vote down vote up
def _generate_added_field(self, app_label, model_name, field_name):
        field = self.new_apps.get_model(app_label, model_name)._meta.get_field(field_name)
        # Fields that are foreignkeys/m2ms depend on stuff
        dependencies = []
        if field.remote_field and field.remote_field.model:
            dependencies.extend(self._get_dependencies_for_foreign_key(field))
        # You can't just add NOT NULL fields with no default or fields
        # which don't allow empty strings as default.
        preserve_default = True
        time_fields = (models.DateField, models.DateTimeField, models.TimeField)
        if (not field.null and not field.has_default() and
                not field.many_to_many and
                not (field.blank and field.empty_strings_allowed) and
                not (isinstance(field, time_fields) and field.auto_now)):
            field = field.clone()
            if isinstance(field, time_fields) and field.auto_now_add:
                field.default = self.questioner.ask_auto_now_add_addition(field_name, model_name)
            else:
                field.default = self.questioner.ask_not_null_addition(field_name, model_name)
            preserve_default = False
        self.add_operation(
            app_label,
            operations.AddField(
                model_name=model_name,
                name=field_name,
                field=field,
                preserve_default=preserve_default,
            ),
            dependencies=dependencies,
        ) 
Example #29
Source File: util.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.remote_field, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value) 
Example #30
Source File: util.py    From myblog with GNU Affero General Public License v3.0 5 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.remote_field, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value)