本文档包含Field
的所有API参考,包括Django提供的字段选项和字段类型。
See also
如果内置字段无法实现,您可以尝试使用django-localflavor(documentation),其中包含针对特定国家和文化定制的各种代码段。
另外,您可以轻松地编写您自己的自定义模型字段。
Note
从技术上讲,这些模型在django.db.models.fields
中定义,但为了方便起见,它们被导入到django.db.models
;标准惯例是使用from django.db import models
字段作为models.<Foo>Field
。
以下参数适用于所有字段类型。 全部都是可选的。
null
¶Field.
null
¶如果True
,Django将在数据库中将空值存储为NULL
。 默认值是False
。
避免在基于字符串的字段(如CharField
和TextField
)上使用null
。 如果一个基于字符串的字段有null = True
,这意味着它有两个可能的“无数据”值:NULL
和空字符串。 在大多数情况下,对于“无数据”有两个可能的值是多余的,Django约定是使用空字符串,而不是NULL
。 一个例外是当CharField
同时设置unique = True
和blank = True
时。 在这种情况下,当使用空值保存多个对象时,需要null = True
以避免唯一的约束违规。
对于基于字符串和非基于字符串的字段,如果您希望允许表单中的空值,则还需要设置blank = True
,如null
参数仅影响数据库存储(请参阅blank
)。
Note
当使用Oracle数据库后端时,无论此属性如何,都将存储NULL
值以表示空字符串。
如果您想接受null
值与BooleanField
,请改为使用NullBooleanField
。
blank
¶Field.
blank
¶If True
, the field is allowed to be blank. Default is False
.
请注意,这不同于null
。 null
纯粹与数据库相关,而blank
与验证相关。 如果一个字段有blank = True
,表单验证将允许输入一个空值。
如果一个字段有blank = False
,则该字段将是必需的。
choices
¶Field.
choices
¶一个可迭代的(例如,一个列表或元组),它本身就包含两个项目的可迭代项(例如[(A, B), (A, B) ...]
)作为该字段的选项。 如果这是给定的,默认表单小部件将是一个选择框与这些选择而不是标准文本字段。
每个元组中的第一个元素是要在模型上设置的实际值,第二个元素是人类可读的名称。 For example:
YEAR_IN_SCHOOL_CHOICES = (
('FR', 'Freshman'),
('SO', 'Sophomore'),
('JR', 'Junior'),
('SR', 'Senior'),
)
通常,最好在模型类中定义选项,并为每个值定义一个适当命名的常量:
from django.db import models
class Student(models.Model):
FRESHMAN = 'FR'
SOPHOMORE = 'SO'
JUNIOR = 'JR'
SENIOR = 'SR'
YEAR_IN_SCHOOL_CHOICES = (
(FRESHMAN, 'Freshman'),
(SOPHOMORE, 'Sophomore'),
(JUNIOR, 'Junior'),
(SENIOR, 'Senior'),
)
year_in_school = models.CharField(
max_length=2,
choices=YEAR_IN_SCHOOL_CHOICES,
default=FRESHMAN,
)
def is_upperclass(self):
return self.year_in_school in (self.JUNIOR, self.SENIOR)
尽管您可以在模型类之外定义一个选择列表,然后引用它,但为模型类中的每个选项定义选项和名称会将所有这些信息与使用它的类相关联,并使得选择易于引用(例如,Student.SOPHOMORE
可以在导入了Student
模型的任何地方使用)。
您还可以将可用选项收集到可用于组织目的的命名组中:
MEDIA_CHOICES = (
('Audio', (
('vinyl', 'Vinyl'),
('cd', 'CD'),
)
),
('Video', (
('vhs', 'VHS Tape'),
('dvd', 'DVD'),
)
),
('unknown', 'Unknown'),
)
每个元组中的第一个元素是要应用于该组的名称。 第二个元素是2元组的迭代,每个2元组包含一个值和一个可读的名称作为选项。 分组选项可以与单个列表中的未分组选项组合(例如本例中的unknown选项)。
对于每个设置了choice
的模型字段,Django都会添加一个方法来检索字段当前值的人类可读名称。 请参阅数据库API文档中的get_FOO_display()
。
请注意,选择可以是任何可迭代对象 - 不一定是列表或元组。
这可以让你动态地构建选择。 但是如果你发现你需要动态的choices
,那么你最好改换使用使用有ForeignKey
的合适的数据库表。 选择
适用于静态数据,如果有的话变化不大。
除非blank = False
与default
一起在字段中设置,否则选择框将使用包含“---------”
的标签进行渲染。 要覆盖此行为,请将元组添加到包含None
的choices
中;例如(None, 'Your String For Display')
。
或者,您可以使用一个空字符串,而不是None
,如果这是有意义的 - 比如在CharField
上。
db_column
¶Field.
db_column
¶用于此字段的数据库列的名称。 如果没有给出,Django将使用该字段的名称。
如果您的数据库列名是SQL保留字,或者包含Python变量名中不允许使用的字符 - 特别是连字符 - 这没关系。 Django在幕后引用列名和表名。
db_tablespace
¶Field.
db_tablespace
¶如果此字段已编入索引,则数据库表空间的名称会被用于此字段索引。 缺省值是项目的DEFAULT_INDEX_TABLESPACE
设置(如果已设置)或模型的db_tablespace
(如果有)。 如果后端不支持索引的表空间,则忽略此选项。
default
¶Field.
default
¶字段的默认值。 这可以是一个值或一个可调用的对象。 如果可调用,则每次创建新对象时都会调用它。
默认不能是可变对象(模型实例,list
,set
等),因为对该对象的同一实例的引用将用作所有新模型实例中的默认值。 相反,将所需的默认值包装为可调用的。 例如,如果你想为JSONField
指定一个默认的dict
,可以使用一个函数:
def contact_default():
return {"email": "to1@example.com"}
contact_info = JSONField("ContactInfo", default=contact_default)
lambda
不能用于像default
这样的字段选项,因为它们不能被迁移序列化。 查看该文档以了解其他警告。
对于映射到模型实例的ForeignKey
等字段,缺省值应该是它们引用字段的值(pk
除非to_field
设置了),而不是模型实例。
当创建新的模型实例并且未为该字段提供值时使用默认值。 当该字段是主键时,字段设置为None
时也使用默认值。
error_messages
¶Field.
error_messages
¶使用error_messages
参数可以覆盖该字段将引发的默认消息。 传入一个字典,其中包含与要覆盖的错误消息相匹配的密钥。
错误消息键包括null
, blank
, invalid
, invalid_choice
, unique
, and unique_for_date
。 为下面的字段类型部分中的每个字段指定其他错误消息键。
这些错误消息通常不会传播到表单。 请参阅有关模型的error_messages的注意事项。
help_text
¶Field.
help_text
¶使用表单小部件显示额外的“帮助”文本。 即使您的字段未在表单上使用,它也可以作为一个相当不错的文档。
请注意,此值在自动生成的表单中不会进行转义。 如果您愿意,可以在help_text
中包含HTML。 For example:
help_text="Please use the following format: <em>YYYY-MM-DD</em>."
或者,您可以使用纯文本和django.utils.html.escape()
来转义任何HTML特殊字符。 确保您转义可能来自不受信任的用户的任何帮助文本,以避免跨站点脚本攻击。
primary_key
¶Field.
primary_key
¶如果True
,则该字段是模型的主键。
如果您没有为模型中的任何字段指定primary_key = True
,Django将自动添加AutoField
来保存主键,因此您无需设置primary_key = True
,除非您想覆盖默认的主键行为。 有关更多信息,请参阅自动主键字段。
primary_key = True
意味着null = False
和unique = True
。 一个对象只允许有一个主键。
主键字段是只读的。 如果您更改现有对象上主键的值并保存它,则会在旧对象旁边创建一个新对象。
unique
¶Field.
unique
¶如果True
,则该字段在整个表格中必须是唯一的。
这是在数据库级和模型验证实施的。 如果您尝试在unique
字段中保存具有重复值的模型,则模型的save()
方法将引发django.db.IntegrityError
。
此选项在ManyToManyField
和OneToOneField
以外的所有字段类型中均有效。
请注意,当unique
为True
时,您不需要指定db_index
,因为unique
意味着创建索引。
在旧版本中,unique = True
不能用于FileField
。
unique_for_date
¶Field.
unique_for_date
¶将此设置为DateField
或DateTimeField
的名称,以要求此字段对于日期字段的值是唯一的。
例如,如果您有一个字段title
的unique_for_date =“pub_date”
,那么Django将不允许输入两个实体记录具有相同title
和pub_date
。
请注意,如果您将其设置为指向DateTimeField
,则只会考虑该字段的日期部分。 此外,当USE_TZ
为True
时,检查的依据是当前时区保存对象的时间。
这在模型验证期间由Model.validate_unique()
实施,但不在数据库层级。 如果任何unique_for_date
约束涉及不属于ModelForm
的字段(例如,如果其中一个字段在exclude
中列出或者editable = False
),Model.validate_unique()
将跳过对特定约束的验证。
verbose_name
¶Field.
verbose_name
¶该字段的人类可读名称。 如果没有给出详细名称,Django将使用该字段的属性名称自动创建它,并将下划线转换为空格。 请参见详细字段名称。
validators
¶Field.
validators
¶要为此字段运行的验证程序列表。 有关更多信息,请参阅验证器文档。
Field
implements the lookup registration API.
The API can be used to customize which lookups are available for a field class, and
how lookups are fetched from a field.
AutoField
¶AutoFields是根据ID自增的IntegerField
字段。 通常不会直接使用到此字段。如果没有特殊定义,主键字段会自动添加到模型中。 参考 Automatic primary key fields.
BigIntegerField
¶是64位整形,类似IntegerField
但数字范围从-9223372036854775808
到9223372036854775807
. 默认的widget是TextInput
.
BinaryField
¶A field to store raw binary data. It only supports bytes
assignment. 注意本字段仅有限制的功能。 比如,BinaryField
不能作为Queryset的筛选条件。 也不能将BinaryField
包含到ModelForm
中。
Abusing BinaryField
Although you might think about storing files in the database, consider that it is bad design in 99% of the cases. This field is not a replacement for proper static files handling.
BooleanField
¶真/假字段。
此字段的默认表单窗口小部件是CheckboxInput
。
如果需要接受null
值,请改用NullBooleanField
。
当未定义Field.default
时,BooleanField
的默认值为无
。
CharField
¶字符串字段,用于小到大的字符串。
对于字数多的文本,请使用TextField
。
此字段的默认表单窗口小部件是TextInput
。
CharField
有一个额外的必需参数:
CharField.
max_length
¶字段的最大长度(以字符为单位)。 max_length在数据库级别和Django的验证中强制执行。
Note
如果您正在编写一个必须可移植到多个数据库后端的应用程序,您应该知道某些后端的max_length
存在限制。 有关详细信息,请参阅数据库后端说明。
DateField
¶日期,由Python以datetime.date
实例表示。 有一些额外的可选参数:
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()
此字段的默认表单窗口小部件是TextInput
。 管理员添加了一个JavaScript日历,以及“今天”的快捷方式。 包含一个额外的invalid_date
错误消息密钥。
选项auto_now_add
,auto_now
和默认
是互斥的。
这些选项的任何组合都将导致错误。
Note
按照当前的实现,将auto_now
或auto_now_add
设置为True
将导致该字段具有editable = False
和 blank = True
设置。
Note
auto_now
和auto_now_add
选项将始终在创建或更新时使用默认时区中的日期。 如果您需要不同的东西,您可能需要考虑简单地使用您自己的可调用默认值或覆盖save()
而不是使用auto_now
或auto_now_add
;或者使用DateTimeField
而不是DateField
,并决定如何在显示时处理从datetime到date的转换。
DateTimeField
¶用一个Python的datetime.datetime
对象同时保存日期和时间。
采用与DateField
相同的额外参数。
此字段的默认表单窗口小部件是单个TextInput
。 管理员使用两个单独的TextInput
小部件和JavaScript快捷方式。
DecimalField
¶一个固定精度的十进制数,用Python中的一个Decimal
实例表示。 Has two required arguments:
DecimalField.
max_digits
¶数字中允许的最大位数。 请注意,此数字必须大于或等于decimal_places
。
DecimalField.
decimal_places
¶与号码一起存储的小数位数。
For example, to store numbers up to 999
with a resolution of 2 decimal
places, you’d use:
models.DecimalField(..., max_digits=5, decimal_places=2)
And to store numbers up to approximately one billion with a resolution of 10 decimal places:
models.DecimalField(..., max_digits=19, decimal_places=10)
The default form widget for this field is a NumberInput
when localize
is False
or
TextInput
otherwise.
Note
For more information about the differences between the
FloatField
and DecimalField
classes, please
see FloatField vs. DecimalField.
DurationField
¶A field for storing periods of time - modeled in Python by
timedelta
. When used on PostgreSQL, the data type
used is an interval
and on Oracle the data type is INTERVAL DAY(9) TO
SECOND(6)
. Otherwise a bigint
of microseconds is used.
Note
Arithmetic with DurationField
works in most cases. However on all
databases other than PostgreSQL, comparing the value of a DurationField
to arithmetic on DateTimeField
instances will not work as expected.
EmailField
¶A CharField
that checks that the value is a valid email address. It
uses EmailValidator
to validate the input.
FileField
¶文件上传字段。
Note
不支持primary_key
参数,如果使用,则会引发错误。
有两个可选参数:
FileField.
upload_to
¶该属性提供了一种设置上传目录和文件名的方法,可以通过两种方式进行设置。 在这两种情况下,该值都传递给Storage.save()
方法。
如果你指定一个字符串值,它可能包含strftime()
格式,它将被文件上传的日期/时间所取代(这样上传的文件不会都堆在给定的单个目录里)。 例如:
class MyModel(models.Model):
# file will be uploaded to MEDIA_ROOT/uploads
upload = models.FileField(upload_to='uploads/')
# or...
# file will be saved to MEDIA_ROOT/uploads/2015/01/30
upload = models.FileField(upload_to='uploads/%Y/%m/%d/')
如果您使用的是默认的FileSystemStorage
,则字符串值将被添加到您的MEDIA_ROOT
路径中,以形成存储上传文件的本地文件系统上的位置。 如果您使用的是不同的存储,请检查存储的文档以了解它如何处理upload_to
。
upload_to
也可以是可调用的,就像函数一样。 它会被调用来获取上传路径,包括文件名。 这个可调用的方法必须接受两个参数,并返回一个Unix样式的路径(带正斜杠)传递给存储系统。 这两个参数是:
Argument | Description |
---|---|
instance |
一个 在大多数情况下,这个对象还没有被保存到数据库中,所以如果它使用默认的 |
filename |
最初提供给该文件的文件名。 在确定最终目的地路径时,这可能会也可能不会被考虑到。 |
For example:
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return 'user_{0}/{1}'.format(instance.user.id, filename)
class MyModel(models.Model):
upload = models.FileField(upload_to=user_directory_path)
该字段的默认表单窗口小部件是ClearableFileInput
。
在模型中使用FileField
或ImageField
(见下文)需要几个步骤:
MEDIA_ROOT
定义为您希望Django存储上传文件的目录的完整路径。
(对于性能,这些文件不存储在数据库中。) 将MEDIA_URL
定义为该目录的基本公用URL。 确保该目录可由Web服务器的用户帐户写入。FileField
或ImageField
添加到您的模型中,定义upload_to
选项以指定MEDIA_ROOT
的子目录用于上传的文件。MEDIA_ROOT
相关的)。 你很可能会想使用Django提供的方便的url
属性。 例如,如果你的ImageField
名为mug_shot
,你可以通过{{ object.mug_shot.url }}
获取在template目录下的图片的绝对路径。例如,假设您的MEDIA_ROOT
设置为'/home/media'
,并且upload_to
设置为'photos/%Y/%m/%d'
。 upload_to
的'%Y /%m /%d'
部分为strftime()
格式; '%Y'
是四位数年份,'%m'
是两位数月份,'%d'
是两个数日。 如果您在2007年1月15日上传文件,它将被保存在/ home / media / photos / 2007/01/15
目录中。
如果您想检索上传文件的磁盘文件名或文件大小,可分别使用name
和size
属性;有关可用属性和方法的更多信息,请参阅文件
类引用和管理文件主题指南。
Note
该文件作为将模型保存在数据库中的一部分进行保存,因此在保存模型之前,不能依赖磁盘上使用的实际文件名。
上传文件的相对URL可以使用url
属性获取。 在内部,它调用底层Storage
类的url()
方法。
请注意,无论何时处理上传的文件,都应密切关注您上传的文件以及它们的类型,以避免安全漏洞。 验证所有上传的文件,以确保文件是您认为的文件。 例如,如果您盲目地让某人上传文件(如果没有进行验证)到Web服务器文档根目录中的目录中,则有人可以上传CGI或PHP脚本,并通过访问您网站上的URL来执行该脚本。 不要允许这种行为。
还要注意,即使是上传的HTML文件,由于它可以被浏览器执行(尽管不是由服务器执行),也可能造成与XSS或CSRF攻击等效的安全威胁。
FileField
实例在您的数据库中创建为默认最大长度为100个字符的varchar
列。 与其他字段一样,您可以使用max_length
参数更改最大长度。
FileField
and FieldFile
¶当您访问模型上的FileField
时,会为您提供FieldFile
的实例作为访问基础文件的代理。
FieldFile
的API反映了File
的API,其中一个关键区别在于: 由该类包装的对象不一定是Python内置文件对象的包装。 相反,它是Storage.open()
方法的结果的一个包装,它可能是一个File
对象,或者它可能是一个自定义存储的 File
API。
除了从File
继承的API,如read()
和write()
,FieldFile
有一些方法可以用来与底层文件进行交互:
FieldFile.
name
¶文件的名称,包括相关FileField
的存储
根目录的相对路径。
FieldFile.
size
¶底层Storage.size()
方法的结果。
FieldFile.
url
¶通过调用基础Storage
类的url()
方法来访问文件相对URL的只读属性。
以指定的模式
打开或重新打开与此实例关联的文件。 与标准的Python open()
方法不同,它不返回文件描述符。
由于底层文件在访问时隐式打开,因此除了将指针重置为底层文件或更改模式
外,可能不需要调用此方法。
行为与标准Python file.close()
方法类似,并关闭与此实例关联的文件。
This method takes a filename and file contents and passes them to the storage
class for the field, then associates the stored file with the model field.
If you want to manually associate file data with
FileField
instances on your model, the save()
method is used to persist that file data.
Takes two required arguments: name
which is the name of the file, and
content
which is an object containing the file’s contents. The
optional save
argument controls whether or not the model instance is
saved after the file associated with this field has been altered. Defaults to
True
.
Note that the content
argument should be an instance of
django.core.files.File
, not Python’s built-in file object.
You can construct a File
from an existing
Python file object like this:
from django.core.files import File
# Open an existing file using Python's built-in open()
f = open('/path/to/hello.world')
myfile = File(f)
Or you can construct one from a Python string like this:
from django.core.files.base import ContentFile
myfile = ContentFile("hello world")
For more information, see Managing files.
Deletes the file associated with this instance and clears all attributes on
the field. Note: This method will close the file if it happens to be open when
delete()
is called.
The optional save
argument controls whether or not the model instance is
saved after the file associated with this field has been deleted. Defaults to
True
.
Note that when a model is deleted, related files are not deleted. If you need to cleanup orphaned files, you’ll need to handle it yourself (for instance, with a custom management command that can be run manually or scheduled to run periodically via e.g. cron).
FilePathField
¶一个CharField
,它们的选择仅限于文件系统上某个目录中的文件名。 有三个特殊的参数,其中第一个是必需的:
FilePathField.
path
¶Required. FileTrackField
应该从中选择的目录的绝对文件系统路径。 Example: "/home/images"
.
FilePathField.
match
¶Optional. A regular expression, as a string, that FilePathField
will use to filter filenames. Note that the regex will be applied to the
base filename, not the full path. Example: "foo.*\.txt$"
, which will
match a file called foo23.txt
but not bar.txt
or foo23.png
.
FilePathField.
recursive
¶Optional. Either True
or False
. Default is False
. Specifies
whether all subdirectories of path
should be included
FilePathField.
allow_files
¶Optional. Either True
or False
. Default is True
. Specifies
whether files in the specified location should be included. Either this or
allow_folders
must be True
.
FilePathField.
allow_folders
¶Optional. Either True
or False
. Default is False
. Specifies
whether folders in the specified location should be included. Either this
or allow_files
must be True
.
当然,这些参数可以一起使用。
The one potential gotcha is that match
applies to the
base filename, not the full path. So, this example:
FilePathField(path="/home/images", match="foo.*", recursive=True)
…will match /home/images/foo.png
but not /home/images/foo/bar.png
because the match
applies to the base filename
(foo.png
and bar.png
).
FilePathField
instances are created in your database as varchar
columns with a default max length of 100 characters. As with other fields, you
can change the maximum length using the max_length
argument.
FloatField
¶A floating-point number represented in Python by a float
instance.
The default form widget for this field is a NumberInput
when localize
is False
or
TextInput
otherwise.
FloatField
vs. DecimalField
The FloatField
class is sometimes mixed up with the
DecimalField
class. Although they both represent real numbers, they
represent those numbers differently. FloatField
uses Python’s float
type internally, while DecimalField
uses Python’s Decimal
type. For
information on the difference between the two, see Python’s documentation
for the decimal
module.
ImageField
¶ImageField
(upload_to=None, height_field=None, width_field=None, max_length=100, **options)[source]¶Inherits all attributes and methods from FileField
, but also
validates that the uploaded object is a valid image.
In addition to the special attributes that are available for FileField
,
an ImageField
also has height
and width
attributes.
To facilitate querying on those attributes, ImageField
has two extra
optional arguments:
ImageField.
height_field
¶Name of a model field which will be auto-populated with the height of the image each time the model instance is saved.
ImageField.
width_field
¶Name of a model field which will be auto-populated with the width of the image each time the model instance is saved.
Requires the Pillow library.
ImageField
instances are created in your database as varchar
columns with a default max length of 100 characters. As with other fields, you
can change the maximum length using the max_length
argument.
The default form widget for this field is a
ClearableFileInput
.
IntegerField
¶An integer. Values from -2147483648
to 2147483647
are safe in all
databases supported by Django. The default form widget for this field is a
NumberInput
when localize
is False
or TextInput
otherwise.
GenericIPAddressField
¶An IPv4 or IPv6 address, in string format (e.g. 192.0.2.30
or
2a02:42fe::4
). The default form widget for this field is a
TextInput
.
The IPv6 address normalization follows RFC 4291#section-2.2 section 2.2,
including using the IPv4 format suggested in paragraph 3 of that section, like
::ffff:192.0.2.0
. For example, 2001:0::0:01
would be normalized to
2001::1
, and ::ffff:0a0a:0a0a
to ::ffff:10.10.10.10
. All characters
are converted to lowercase.
GenericIPAddressField.
protocol
¶Limits valid inputs to the specified protocol.
Accepted values are 'both'
(default), 'IPv4'
or 'IPv6'
. Matching is case insensitive.
GenericIPAddressField.
unpack_ipv4
¶Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1
.
If this option is enabled that address would be unpacked to
192.0.2.1
. Default is disabled. Can only be used
when protocol
is set to 'both'
.
If you allow for blank values, you have to allow for null values since blank values are stored as null.
NullBooleanField
¶Like a BooleanField
, but allows NULL
as one of the options. Use
this instead of a BooleanField
with null=True
. The default form
widget for this field is a NullBooleanSelect
.
PositiveIntegerField
¶Like an IntegerField
, but must be either positive or zero (0
).
Values from 0
to 2147483647
are safe in all databases supported by
Django. The value 0
is accepted for backward compatibility reasons.
PositiveSmallIntegerField
¶像PositiveIntegerField
,但只允许某些特定的值(取决于数据库)。 从0
到32767
的值在Django支持的所有数据库中都是安全的。
SlugField
¶Slug is a newspaper term. A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs.
Like a CharField, you can specify max_length
(read the note
about database portability and max_length
in that section,
too). If max_length
is not specified, Django will use a
default length of 50.
Implies setting Field.db_index
to True
.
It is often useful to automatically prepopulate a SlugField based on the value
of some other value. You can do this automatically in the admin using
prepopulated_fields
.
SlugField.
allow_unicode
¶If True
, the field accepts Unicode letters in addition to ASCII
letters. Defaults to False
.
SmallIntegerField
¶Like an IntegerField
, but only allows values under a certain
(database-dependent) point. Values from -32768
to 32767
are safe in all
databases supported by Django.
TextField
¶长文本字段。 此字段的默认表单窗口小部件是Textarea
。
如果指定max_length
属性,它将反映在自动生成的表单字段的Textarea
小部件中。
但是,它不会在模型或数据库级别强制执行。 如果您有这样的需求,请采用CharField
。
TimeField
¶A time, represented in Python by a datetime.time
instance. Accepts the same
auto-population options as DateField
.
The default form widget for this field is a TextInput
.
The admin adds some JavaScript shortcuts.
URLField
¶A CharField
for a URL.
The default form widget for this field is a TextInput
.
Like all CharField
subclasses, URLField
takes the optional
max_length
argument. If you don’t specify
max_length
, a default of 200 is used.
UUIDField
¶A field for storing universally unique identifiers. Uses Python’s
UUID
class. When used on PostgreSQL, this stores in a
uuid
datatype, otherwise in a char(32)
.
Universally unique identifiers are a good alternative to AutoField
for
primary_key
. The database will not generate the UUID for you, so
it is recommended to use default
:
import uuid
from django.db import models
class MyUUIDModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
# other fields
Note that a callable (with the parentheses omitted) is passed to default
,
not an instance of UUID
.
Field
[source]¶Field
is an abstract class that represents a database table column.
Django uses fields to create the database table (db_type()
), to map
Python types to database (get_prep_value()
) and vice-versa
(from_db_value()
).
A field is thus a fundamental piece in different Django APIs, notably,
models
and querysets
.
In models, a field is instantiated as a class attribute and represents a
particular table column, see Models. It has attributes
such as null
and unique
, and methods that Django uses to
map the field value to database-specific values.
A Field
is a subclass of
RegisterLookupMixin
and thus both
Transform
and
Lookup
can be registered on it to be used
in QuerySet
s (e.g. field_name__exact="foo"
). All built-in
lookups are registered by default.
All of Django’s built-in fields, such as CharField
, are particular
implementations of Field
. If you need a custom field, you can either
subclass any of the built-in fields or write a Field
from scratch. In
either case, see Writing custom model fields.
description
¶A verbose description of the field, e.g. for the
django.contrib.admindocs
application.
The description can be of the form:
description = _("String (up to %(max_length)s)")
where the arguments are interpolated from the field’s __dict__
.
To map a Field
to a database-specific type, Django exposes several
methods:
get_internal_type
()[source]¶Returns a string naming this field for backend specific purposes. By default, it returns the class name.
See Emulating built-in field types for usage in custom fields.
db_type
(connection)[source]¶Returns the database column data type for the Field
, taking
into account the connection
.
See Custom database types for usage in custom fields.
rel_db_type
(connection)[source]¶Returns the database column data type for fields such as ForeignKey
and OneToOneField
that point to the Field
, taking
into account the connection
.
See Custom database types for usage in custom fields.
There are three main situations where Django needs to interact with the database backend and fields:
When querying, get_db_prep_value()
and get_prep_value()
are used:
get_prep_value
(value)[source]¶value
is the current value of the model’s attribute, and the method
should return data in a format that has been prepared for use as a
parameter in a query.
See Converting Python objects to query values for usage.
get_db_prep_value
(value, connection, prepared=False)[source]¶Converts value
to a backend-specific value. By default it returns
value
if prepared=True
and get_prep_value()
if is
False
.
See Converting query values to database values for usage.
When loading data, from_db_value()
is used:
from_db_value
(value, expression, connection)¶Converts a value as returned by the database to a Python object. It is
the reverse of get_prep_value()
.
This method is not used for most built-in fields as the database backend already returns the correct Python type, or the backend itself does the conversion.
See Converting values to Python objects for usage.
Note
For performance reasons, from_db_value
is not implemented as a
no-op on fields which do not require it (all Django fields).
Consequently you may not call super
in your definition.
When saving, pre_save()
and get_db_prep_save()
are used:
get_db_prep_save
(value, connection)[source]¶Same as the get_db_prep_value()
, but called when the field value
must be saved to the database. By default returns
get_db_prep_value()
.
pre_save
(model_instance, add)[source]¶Method called prior to get_db_prep_save()
to prepare the value
before being saved (e.g. for DateField.auto_now
).
model_instance
is the instance this field belongs to and add
is whether the instance is being saved to the database for the first
time.
It should return the value of the appropriate attribute from
model_instance
for this field. The attribute name is in
self.attname
(this is set up by Field
).
See Preprocessing values before saving for usage.
Fields often receive their values as a different type, either from serialization or from forms.
to_python
(value)[source]¶Converts the value into the correct Python object. It acts as the
reverse of value_to_string()
, and is also called in
clean()
.
See Converting values to Python objects for usage.
Besides saving to the database, the field also needs to know how to serialize its value:
value_to_string
(obj)[source]¶Converts obj
to a string. Used to serialize the value of the field.
See Converting field data for serialization for usage.
When using model forms
, the Field
needs to know which form field it should be represented by:
formfield
(form_class=None, choices_form_class=None, **kwargs)[source]¶Returns the default django.forms.Field
of this field for
ModelForm
.
By default, if both form_class
and choices_form_class
are
None
, it uses CharField
. If the field has
choices
and choices_form_class
isn’t specified, it uses TypedChoiceField
.
See Specifying the form field for a model field for usage.
deconstruct
()[source]¶Returns a 4-tuple with enough information to recreate the field:
"django.db.models.IntegerField"
).
This should be the most portable version, so less specific may be better.This method must be added to fields prior to 1.7 to migrate its data using Migrations.
Every Field
instance contains several attributes that allow
introspecting its behavior. Use these attributes instead of isinstance
checks when you need to write code that depends on a field’s functionality.
These attributes can be used together with the Model._meta API to narrow down a search for specific field types.
Custom model fields should implement these flags.
Field.
auto_created
¶布尔标志,指示是否自动创建字段,例如模型继承使用的OneToOneField
。
Field.
concrete
¶布尔标志,指示该字段是否具有与之关联的数据库列。
Boolean flag that indicates if a field is used to back another non-hidden
field’s functionality (e.g. the content_type
and object_id
fields
that make up a GenericForeignKey
). The hidden
flag is used to
distinguish what constitutes the public subset of fields on the model from
all the fields on the model.
Note
Options.get_fields()
excludes hidden fields by default. Pass in include_hidden=True
to
return hidden fields in the results.
Field.
is_relation
¶Boolean flag that indicates if a field contains references to one or
more other models for its functionality (e.g. ForeignKey
,
ManyToManyField
, OneToOneField
, etc.).
Field.
model
¶Returns the model on which the field is defined. If a field is defined on
a superclass of a model, model
will refer to the superclass, not the
class of the instance.
These attributes are used to query for the cardinality and other details of a
relation. These attribute are present on all fields; however, they will only
have boolean values (rather than None
) if the field is a relation type
(Field.is_relation=True
).
Field.
many_to_many
¶Boolean flag that is True
if the field has a many-to-many relation;
False
otherwise. The only field included with Django where this is
True
is ManyToManyField
.
Field.
many_to_one
¶Boolean flag that is True
if the field has a many-to-one relation, such
as a ForeignKey
; False
otherwise.
Field.
one_to_many
¶Boolean flag that is True
if the field has a one-to-many relation, such
as a GenericRelation
or the reverse of a ForeignKey
; False
otherwise.
Field.
one_to_one
¶Boolean flag that is True
if the field has a one-to-one relation, such
as a OneToOneField
; False
otherwise.
Points to the model the field relates to. For example, Author
in
ForeignKey(Author, on_delete=models.CASCADE)
. The related_model
for
a GenericForeignKey
is always None
.
Jan 17, 2018