DateField – Django 模型
DateField 是一个存储日期的字段,在Python中由 datetime.date 实例表示。顾名思义,该字段用于存储在Python中创建的日期对象。此字段的默认表单小部件是 TextInput。管理员可以显式添加 JavaScript 日历和“今天”的快捷方式。
句法:
field_name = models.DateField(**options)
DateField 有以下额外的可选参数——
DateField.auto_now
- 每次保存对象时自动将字段设置为现在。对于“最后修改”的时间戳很有用。请注意,始终使用当前日期;它不仅仅是您可以覆盖的默认值。
该字段仅在调用 Model.save() 时自动更新。以其他方式(例如 QuerySet.update())对其他字段进行更新时,该字段不会更新,尽管您可以在类似的更新中为该字段指定自定义值。
DateField.auto_now_add
- 首次创建对象时自动将字段设置为现在。用于创建时间戳。请注意,始终使用当前日期;它不仅仅是您可以覆盖的默认值。因此,即使您在创建对象时为此字段设置了值,它也会被忽略。如果您希望能够修改此字段,请设置以下内容而不是 auto_now_add=True:
- 对于DateField:default=date.today – 从 datetime.date.today()
- 对于DateTimeField:default=timezone.now – 来自 django.utils.timezone.now()
Note: The options auto_now_add, auto_now, and default are mutually exclusive. Any combination of these options will result in an error.
Django 模型 DateField 解释
使用示例说明 DateField。考虑一个名为 geeksforgeeks 的项目,它有一个名为 geeks 的应用程序。
Refer to the following articles to check how to create a project and an app in Django.
- How to Create a Basic Project using MVT in Django?
- How to Create an App in Django ?
在极客应用的models.py文件中输入以下代码。
Python3
from django.db import models
from django.db.models import Model
# Create your models here.
class GeeksModel(Model):
geeks_field = models.DateField()
Python3
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'geeks',
]
Python3
# Generated by Django 2.2.5 on 2019-09-25 06:00
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name ='GeeksModel',
fields =[
('id',
models.AutoField(
auto_created = True,
primary_key = True,
serialize = False,
verbose_name ='ID'
)),
('geeks_field', models.DateField()),
],
),
]
Python3
# importing the model
# from geeks app
from geeks.models import GeeksModel
# importing datetime module
import datetime
# creating an instance of
# datetime.date
d = datetime.date(1997, 10, 19)
# creating an instance of
# GeeksModel
geek_object = GeeksModel.objects.create(geeks_field = d)
geek_object.save()
将极客应用添加到 INSTALLED_APPS
Python3
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'geeks',
]
现在,当我们从终端运行 makemigrations 命令时,
Python manage.py makemigrations
将在 geeks 目录中创建一个名为 migrations 的新文件夹,其中包含一个名为 0001_initial.py 的文件
Python3
# Generated by Django 2.2.5 on 2019-09-25 06:00
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name ='GeeksModel',
fields =[
('id',
models.AutoField(
auto_created = True,
primary_key = True,
serialize = False,
verbose_name ='ID'
)),
('geeks_field', models.DateField()),
],
),
]
现在运行,
Python manage.py migrate
因此,当您在项目上运行迁移时,会创建一个 geeks_field DateField 。它是一个存储 datetime.date Python对象的字段。
如何使用日期字段?
DateField 用于在数据库中存储Python datetime.date 实例。可以在数据库中使用相同的日期存储任何类型的日期。让我们尝试在上面创建的模型中存储一个日期。
Python3
# importing the model
# from geeks app
from geeks.models import GeeksModel
# importing datetime module
import datetime
# creating an instance of
# datetime.date
d = datetime.date(1997, 10, 19)
# creating an instance of
# GeeksModel
geek_object = GeeksModel.objects.create(geeks_field = d)
geek_object.save()
现在让我们在管理服务器中检查它。我们已经创建了 GeeksModel 的一个实例。
字段选项
字段选项是赋予每个字段的参数,用于应用某些约束或将特定特征赋予特定字段。例如,向 DateField 添加参数 null = True 将使其能够将该表的空值存储在关系数据库中。
以下是 DateField 可以使用的字段选项和属性。Field Options Description Null If True, Django will store empty values as NULL in the database. Default is False. Blank If True, the field is allowed to be blank. Default is False. db_column The name of the database column to use for this field. If this isn’t given, Django will use the field’s name.
db_index If True, a database index will be created for this field db_tablespace The name of the database tablespace to use for this field’s index, if this field is indexed. The default is the project’s DEFAULT_INDEX_TABLESPACE setting, if set, or the db_tablespace of the model, if any. If the backend doesn’t support tablespaces for indexes, this option is ignored. Default The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.
help_text Extra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form.
primary_key If True, this field is the primary key for the model. editable If False, the field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True.
error_messages The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override.
help_text Extra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form.
verbose_name A human-readable name for the field. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces.
validators A list of validators to run for this field. See the validators documentation for more information.
Unique If True, this field must be unique throughout the table.