当前位置: 首页>>代码示例>>Python>>正文


Python models.DateTimeField方法代码示例

本文整理汇总了Python中django.db.models.DateTimeField方法的典型用法代码示例。如果您正苦于以下问题:Python models.DateTimeField方法的具体用法?Python models.DateTimeField怎么用?Python models.DateTimeField使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.db.models的用法示例。


在下文中一共展示了models.DateTimeField方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: display_for_field

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import DateTimeField [as 别名]
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) 
开发者ID:stormsha,项目名称:StormOnline,代码行数:25,代码来源:util.py

示例2: _make_single_date_lookup

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import DateTimeField [as 别名]
def _make_single_date_lookup(self, date):
        """
        Get the lookup kwargs for filtering on a single date.

        If the date field is a DateTimeField, we can't just filter on
        date_field=date because that doesn't take the time into account.
        """
        date_field = self.get_date_field()
        if self.uses_datetime_field:
            since = self._make_date_lookup_arg(date)
            until = self._make_date_lookup_arg(date + datetime.timedelta(days=1))
            return {
                '%s__gte' % date_field: since,
                '%s__lt' % date_field: until,
            }
        else:
            # Skip self._make_date_lookup_arg, it's a no-op in this branch.
            return {date_field: date} 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:20,代码来源:dates.py

示例3: value_to_db_datetime

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import DateTimeField [as 别名]
def value_to_db_datetime(self, value):
        """
        Transform a datetime value to an object compatible with what is expected
        by the backend driver for datetime columns.

        If naive datetime is passed assumes that is in UTC. Normally Django
        models.DateTimeField makes sure that if USE_TZ is True passed datetime
        is timezone aware.
        """

        if value is None:
            return None

        # cx_Oracle doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = value.astimezone(timezone.utc).replace(tzinfo=None)
            else:
                raise ValueError("Oracle backend does not support timezone-aware datetimes when USE_TZ is False.")

        return Oracle_datetime.from_datetime(value) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:23,代码来源:operations.py

示例4: display_for_field

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import DateTimeField [as 别名]
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) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:26,代码来源:utils.py

示例5: _check_date_hierarchy

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import DateTimeField [as 别名]
def _check_date_hierarchy(self, cls, model):
        """ Check that date_hierarchy refers to DateField or DateTimeField. """

        if cls.date_hierarchy is None:
            return []
        else:
            try:
                field = model._meta.get_field(cls.date_hierarchy)
            except FieldDoesNotExist:
                return refer_to_missing_field(option='date_hierarchy',
                                              field=cls.date_hierarchy,
                                              model=model, obj=cls, id='admin.E127')
            else:
                if not isinstance(field, (models.DateField, models.DateTimeField)):
                    return must_be('a DateField or DateTimeField', option='date_hierarchy',
                                   obj=cls, id='admin.E128')
                else:
                    return [] 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:20,代码来源:checks.py

示例6: validate_prepopulated_fields

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import DateTimeField [as 别名]
def validate_prepopulated_fields(self, cls, model):
        " Validate that prepopulated_fields if a dictionary  containing allowed field types. "
        # prepopulated_fields
        if hasattr(cls, 'prepopulated_fields'):
            check_isdict(cls, 'prepopulated_fields', cls.prepopulated_fields)
            for field, val in cls.prepopulated_fields.items():
                f = get_field(cls, model, 'prepopulated_fields', field)
                if isinstance(f, (models.DateTimeField, models.ForeignKey,
                        models.ManyToManyField)):
                    raise ImproperlyConfigured("'%s.prepopulated_fields['%s']' "
                            "is either a DateTimeField, ForeignKey or "
                            "ManyToManyField. This isn't allowed."
                            % (cls.__name__, field))
                check_isseq(cls, "prepopulated_fields['%s']" % field, val)
                for idx, f in enumerate(val):
                    get_field(cls, model, "prepopulated_fields['%s'][%d]" % (field, idx), f) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:18,代码来源:validation.py

示例7: adapt_datetimefield_value

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import DateTimeField [as 别名]
def adapt_datetimefield_value(self, value):
        """
        Transform a datetime value to an object compatible with what is expected
        by the backend driver for datetime columns.

        If naive datetime is passed assumes that is in UTC. Normally Django
        models.DateTimeField makes sure that if USE_TZ is True passed datetime
        is timezone aware.
        """

        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        # cx_Oracle doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = timezone.make_naive(value, self.connection.timezone)
            else:
                raise ValueError("Oracle backend does not support timezone-aware datetimes when USE_TZ is False.")

        return Oracle_datetime.from_datetime(value) 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:27,代码来源:operations.py

示例8: datetimes

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import DateTimeField [as 别名]
def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
        """
        Return a list of datetime objects representing all available
        datetimes for the given field_name, scoped to 'kind'.
        """
        assert kind in ("year", "month", "day", "hour", "minute", "second"), \
            "'kind' must be one of 'year', 'month', 'day', 'hour', 'minute' or 'second'."
        assert order in ('ASC', 'DESC'), \
            "'order' must be either 'ASC' or 'DESC'."
        if settings.USE_TZ:
            if tzinfo is None:
                tzinfo = timezone.get_current_timezone()
        else:
            tzinfo = None
        return self.annotate(
            datetimefield=Trunc(field_name, kind, output_field=DateTimeField(), tzinfo=tzinfo),
            plain_field=F(field_name)
        ).values_list(
            'datetimefield', flat=True
        ).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield') 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:22,代码来源:query.py

示例9: display_for_field

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import DateTimeField [as 别名]
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) 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:25,代码来源:utils.py

示例10: _check_prepopulated_fields_key

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import DateTimeField [as 别名]
def _check_prepopulated_fields_key(self, obj, model, field_name, label):
        """ Check a key of `prepopulated_fields` dictionary, i.e. check that it
        is a name of existing field and the field is one of the allowed types.
        """

        try:
            field = model._meta.get_field(field_name)
        except FieldDoesNotExist:
            return refer_to_missing_field(field=field_name, option=label,
                                          model=model, obj=obj, id='admin.E027')
        else:
            if isinstance(field, (models.DateTimeField, models.ForeignKey, models.ManyToManyField)):
                return [
                    checks.Error(
                        "The value of '%s' refers to '%s', which must not be a DateTimeField, "
                        "a ForeignKey, a OneToOneField, or a ManyToManyField." % (label, field_name),
                        obj=obj.__class__,
                        id='admin.E028',
                    )
                ]
            else:
                return [] 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:24,代码来源:checks.py

示例11: populate_tracking_fields

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import DateTimeField [as 别名]
def populate_tracking_fields(apps, schema_editor):
    managers = [
        apps.get_model('hosting', 'Phone')._default_manager.all(),
        apps.get_model('hosting', 'Place')._default_manager.all(),
        apps.get_model('hosting', 'Profile')._default_manager.all(),
        apps.get_model('hosting', 'Website')._default_manager.all(),
    ]

    for objects in managers:
        objects.update(
            deleted_on=Case(
                When(deleted=False, then=None),
                default=F('modified'),
                output_field=DateTimeField())
        )
        objects.update(
            checked_on=Case(
                When(checked=False, then=None),
                default=F('modified'),
                output_field=DateTimeField())
        ) 
开发者ID:tejoesperanto,项目名称:pasportaservo,代码行数:23,代码来源:0029_tracking_fields_using_datetime.py

示例12: display_for_field

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import DateTimeField [as 别名]
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) 
开发者ID:Superbsco,项目名称:weibo-analysis-system,代码行数:25,代码来源:util.py

示例13: resolve_field

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import DateTimeField [as 别名]
def resolve_field(meta):
        type = meta['type']
        rest = merge(filter_dict(
            # Don't allow default='SEQUENCE'
            lambda key, value: not (key=='default' and value=='SEQUENCE'),
            # Ignore these keys
            remove_keys(meta, ['type', 'auto_populate', 'visible', 'geometry_type', 'nullable'])
        ), dict(null=True))
        if type=='string':
            return models.CharField(**rest)
        elif type=='integer':
            return models.IntegerField(**rest)
        elif type=='float':
            return models.FloatField(**rest)
        elif type=='biginteger':
            return models.BigIntegerField(**rest)
        elif type=='geometry':
            return models.GeometryField(geography=False, **rest)
        elif type=='date':
            return models.DateField(**rest)
        elif type=='datetime':
            return models.DateTimeField(**rest) 
开发者ID:CalthorpeAnalytics,项目名称:urbanfootprint,代码行数:24,代码来源:feature_class_creator.py

示例14: load_dates

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import DateTimeField [as 别名]
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)) 
开发者ID:jeeyshe,项目名称:ishare,代码行数:25,代码来源:simpletags.py

示例15: datetimes

# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import DateTimeField [as 别名]
def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
        """
        Return a list of datetime objects representing all available
        datetimes for the given field_name, scoped to 'kind'.
        """
        assert kind in ('year', 'month', 'week', 'day', 'hour', 'minute', 'second'), \
            "'kind' must be one of 'year', 'month', 'week', 'day', 'hour', 'minute', or 'second'."
        assert order in ('ASC', 'DESC'), \
            "'order' must be either 'ASC' or 'DESC'."
        if settings.USE_TZ:
            if tzinfo is None:
                tzinfo = timezone.get_current_timezone()
        else:
            tzinfo = None
        return self.annotate(
            datetimefield=Trunc(field_name, kind, output_field=DateTimeField(), tzinfo=tzinfo),
            plain_field=F(field_name)
        ).values_list(
            'datetimefield', flat=True
        ).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield') 
开发者ID:PacktPublishing,项目名称:Hands-On-Application-Development-with-PyCharm,代码行数:22,代码来源:query.py


注:本文中的django.db.models.DateTimeField方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。