本文整理匯總了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)
示例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}
示例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)
示例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)
示例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 []
示例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)
示例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)
示例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')
示例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)
示例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 []
示例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())
)
示例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)
示例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)
示例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))
示例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')