django 模型字段

2016/6/8 posted in  python

django模型字段

关注django模型字段主要关注模型的几个方面

  • 数据库当中的列类型 (比如: INTEGER, VARCHAR)。
  • 渲染表单时使用的默认HTML 部件(例如,, )。
  • 最低限度的验证需求,它被用在 Django 管理站点和自动生成的表单中。

几个默认字段

null

如果为True,Django 将用NULL 来在数据库中存储空值。 默认值是 False.

blank

如果为True,该字段允许不填。默认为False。

choice

由二项元组构成的一个可迭代对象(例如,列表或元组),用来给字段提供选择项。如果设置了choices ,默认的表单将是一个选择框而不是标准的文本框,而且这个选择框的选项就是choices 中的选项。

    from django.db import models
    class Person(models.Model):
        SHIRT_SIZES = (
            ('S', 'Small'),
            ('M', 'Medium'),
            ('L', 'Large'),
        )
        name = models.CharField(max_length=60)
        shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)
default

字段的默认值。可以是一个值或者可调用对象。如果可调用 ,每有新对象被创建它都会被调用。

help_text

表单部件额外显示的帮助内容,会添加到默认的Form中。即使字段不在表单中使用,它对生成文档也很有用。

primary_key

如果为True,那么这个字段就是模型的主键。如果你没有指定任何一个字段的primary_key=True,Django 就会自动添加一个IntegerField 字段做为主键.

主键字段是只读的。如果你在一个已存在的对象上面更改主键的值并且保存,一个新的对象将会在原有对象之外创建出来。

unique

如果该值设置为 True, 这个数据字段的值在整张表中必须是唯一的

这是一个在数据库级别的强制性动作,并且通过模型来验证。如果你试图用一个重复的值来保存unique 字段,那么一个django.db.IntegrityError就会通过模型的save() 函数抛出来。

注意当设置unique 为True 时,你不需要再指定 db_index,因为unique 本身就意味着一个索引的创建。

db_column

数据库中用来表示该字段的名称。如果未指定,那么Django将会使用Field名作为字段名.

dh_index

若值为 True, 则 django-admin sqlindexes 将会为此字段输出 CREATE INDEX 语句。创建索引

db_tablespace

如果该字段有索引的话,database tablespace的名称将作为该字段的索引名。 如果DEFAULT_INDEX_TABLESPACE 已经设置,则默认值是由DEFAULT_INDEX_TABLESPACE指定, 如果没有设置则由 db_tablespace 指定,如果后台数据库不支持表空间,或者索引,则该选项被忽略

editable

如果设为False, 这个字段将不会出现在 admin 或者其他 ModelForm. 他们也会跳过 模型验证. 默认是True.

error_messages

error_messages 参数能够让你重写默认抛出的错误信息。通过指定 key 来确认你要重写的错误信息。

error_messages 的 key 值包括 null, blank, invalid, invalid_choice, unique, 和 unique_for_date.

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() 将忽略该特殊的约束。

unique_for_month
unique_for_year
verbose_name

一个字段的可读性更高的名称。如果用户没有设定冗余名称字段,Django会自动将该字段属性名中的下划线转换为空格,并用它来创建冗余名称。

validators

该字段将要运行的一个Validator 的列表。

模型类型

自增字段

class AutoField(options)

一个根据实际ID自动增长的IntegerField 。你通常不需要直接使用;如果不指定,一个主键字段将自动添加到你创建的模型中。

BigIntegerField

class BigIntegerField([options])

一个64位整数, 类似于一个 IntegerField ,它的值的范围是 -9223372036854775808 到9223372036854775807之间. 这个字段默认的表单组件是一个TextInput.

BinaryField

class BinaryField([options])
这是一个用来存储原始二进制码的Field. 只支持bytes 赋值,注意这个Field只有很有限的功能。例如,不大可能在一个BinaryField 值的数据上进行查询

Abusing BinaryField

尽管你可能想使用数据库来存储你的文件,但是99%的情况下这都是不好的设计。这个字段 不是替代static files 的合理操作.

BooleanField

class BooleanField(options)
一个 true/false 字段。

此字段的默认表单挂件是一个CheckboxInput.

如果你需要设置null 值,则使用NullBooleanField 来代替BooleanField。

如果Field.default没有指定的话, BooleanField 的默认值是 None。

CharField

class CharField(max_length=None[, options])

一个用来存储从小到很大各种长度的字符串的地方

如果是巨大的文本类型, 可以用 TextField.

这个字段默认的表单样式是 TextInput.

CharField必须接收一个额外的参数:

CharField.max_length
字段的最大字符长度.max_length将在数据库层和Django表单验证中起作用, 用来限定字段的长度.

CommaSeparatedIntegerField

class CommaSeparatedIntegerField(max_length=None[, options])

一个逗号分隔的整数字段。像 CharField一样, 需要一个max_length 参数, 同时数据库移植时也需要注意。

DateField

class DateField([auto_now=False, auto_now_add=False, options])

这是一个使用Python的datetime.date实例表示的日期. 有几个额外的设置参数:

DateField.auto_now
每次保存对象时,自动设置该字段为当前时间。用于"最后一次修改"的时间戳。注意,它总是使用当前日期;和你可以覆盖的那种默认值不一样。

DateField.auto_now_add
当对象第一次被创建时自动设置当前时间。用于创建时间的时间戳. 它总是使用当前日期;和你可以覆盖的那种默认值不一样。

该字段默认对应的表单控件是一个TextInput. 在管理员站点添加了一个JavaScript写的日历控件,和一个“Today"的快捷按钮.包含了一个额外的invalid_date错误消息键.

auto_now_add, auto_now, and default 这些设置是相互排斥的. 他们之间的任何组合将会发生错误的结果.

DateTimeField

class DateTimeField([auto_now=False, auto_now_add=False, options])

它是通过Python datetime.datetime实例表示的日期和时间. 携带了跟DateField一样的额外参数.

该字段默认对应的表单控件是一个单个的TextInput(单文本输入框). 管理界面是使用两个带有 JavaScript控件的 TextInput 文本框.

DecimalField

class DecimalField(max_digits=None, decimal_places=None[, options])

用python中 Decimal 的一个实例来表示十进制浮点数. 有两个 必须的参数:

DecimalField.max_digits
位数总数,包括小数点后的位数。该值必须大于等于decimal_places.

DecimalField.decimal_places
小数点后的数字数量

例如,要保存最大为 999 并有两位小数的数字,你应该使用:

    models.DecimalField(..., max_digits=5, decimal_places=2)

而要存储那些将近10亿,并且要求达到小数点后十位精度的数字:

    models.DecimalField(..., max_digits=19, decimal_places=10)

该字段默认的窗体组件是 TextInput.

DurationField

class DurationField([options])

用作存储一段时间的字段类型 - 类似Python中的timedelta. 当数据库使用的是PostgreSQL, 该数据类型使用的是一个 interval 而在Oracle上,则使用的是 INTERVAL DAY(9) TO SECOND(6). Otherwise a bigint of microseconds is used.

EmailField

class EmailField([max_length=254, options])

一个 CharField 用来检查输入的email地址是否合法。它使用 EmailValidator 来验证输入合法性。

FileField

class FileField([upload_to=None, max_length=100, options])

一个上传文件的字段。

注意

FileField字段不支持primary_key 和unique参数,如果使用会生成 TypeError错误

有两个可选参数:

FileField.upload_to
Changed in Django 1.7:
在旧版本Django中,upload_to 属性是必须要有的;
一个本地文件系统的路径,它将附加到MEDIA_ROOT 设置的后面来确定url 属性的值。

这个路径可以会包含一个strftime() 格式串,它将在文件上传时被替换为实际的日期/时间(这样上传的文件就不会塞满你指定的文件夹)。

它还可以是一个可调用对象如函数,将调用它来获取上传路径,包括文件名。这个可调用对象必须接受两个参数,并且返回一个Unix 风格的路径(带有前向/)给存储系统。将传递的两个参数为:

Argument Description
instance
FileField 定义所在的模型的实例。更准确地说,就是当前文件的所在的那个实例。

大部分情况下,这个实例将还没有保存到数据库中,若它用到默认的AutoField 字段,它的主键字段还可能没有值。

filename The filename that was originally given to the file. This may or may not be taken into account when determining the final destination path.
FileField.storage¶
一个Storage 对象,用于你的文件的存取。参见管理文件 获取如何提供这个对象的细节。

这个字段的默认表单Widget 是ClearableFileInput。

在模型中调用FileField 或 ImageField (见下方) 需如下几步:

在你的settings文件中, 你必须要定义 MEDIA_ROOT 作为Django存储上传文件的路径(从性能上考虑,这些文件不能存在数据库中。) 定义一个 MEDIA_URL 作为基础的URL或者目录。确保这个目录可以被web server使用的账户写入。
在模型中添加FileField 或 ImageField 字段, 定义 upload_to参数,内容是 MEDIA_ROOT 的子目录,用来存放上传的文件。
数据库中存放的仅是这个文件的路径 (相对于MEDIA_ROOT). 你很可能会想用由Django提供的便利的url 属性。比如说, 如果你的ImageField 命名为 mug_shot, 你可以在template中用 {{ object.mug_shot.url }}获得你照片的绝对路径。
例如,如果你的 MEDIA_ROOT设定为 '_home_media',并且 upload_to设定为 'photos_%Y_%m_%d'。 upload_to的'%Y_%m_%d'被strftime()所格式化;'%Y' 将会被格式化为一个四位数的年份, '%m' 被格式化为一个两位数的月份'%d'是两位数日份。如果你在Jan.15.2007上传了一个文件,它将被保存在_home_media_photos/2007/01/15目录下.

如果你想获得上传文件的存盘文件名,或者是文件大小,你可以分别使用 name 和 size 属性; 更多可用属性及方法信息,请参见 File 类索引 和 Managing files 主题指导.

Note

保存的文件作为模型存储在数据库中的一部分,所以在磁盘上使用的实际的文件名在模型保存完毕之前是不可靠的。

上传的文件对应的URL可以通过使用 url 属性获得. 在内部,它会调用 Storage 类下的url()方法.

值得注意的是,无论你在任何时候处理上传文件的需求,你都应该密切关注你的文件将被上传到哪里,上传的文件类型,以避免安全漏洞。认证所有上传文件 以确保那些上传的文件是你所认为的文件。例如,如果你盲目的允许其他人在无需认证的情况下上传文件至你的web服务器的root目录中,那么别人可以上传一个CGI或者PHP脚本然后通过访问一个你网站的URL来执行这个脚本。所以,不要允许这种事情发生。

甚至是上传HTML文件也值得注意,它可以通过浏览器(虽然不是服务器)执行,也可以引发相当于是XSS或者CSRF攻击的安全威胁。

FileField 实例将会在你的数据库中创建一个默认最大长度为100字符的varchar 列。就像其他的fields一样, 你可以用 max_length 参数改变最大长度的值.

FileField 和FieldFile¶

class FieldFile[source]¶
当你添加 FileField 到你的模型中时, 你实际上会获得一个 FieldFile的实例来替代将要访问的文件。 除了继承至 django.core.files.File的功能外, 这个类还有其他属性和方法可以用于访问文件:

FieldFile.url¶
通过潜在Storage 类的url()方法可以只读地访问文件的URL。

FieldFile.open(mode='rb')[source]¶
该方法像标准的Python open() 方法,并可通过 mode参数设置打开模式.

FieldFile.close()[source]¶
该方法像标准的Pythonfile.close() 方法,并关闭相关文件.

FieldFile.save(name, content, save=True)[source]¶
这个方法会将文件名以及文件内容传递到字段的storage类中,并将模型字段与保存好的文件关联. 如果想要手动关联文件数据到你的模型中的 FileField实例, 则save() 方法总是用来保存该数据.

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('_tmp_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")
更多信息, 请参见 Managing files.

FieldFile.delete(save=True)[source]¶
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.

注意,model删除的时候,与之关联的文件并不会被删除。如果你要把文件也清理掉,你需要自己处理。

FilePathField

class FilePathField(path=None[, match=None, recursive=False, max_length=100, options])

一个 CharField ,内容只限于文件系统内特定目录下的文件名。有三个参数, 其中第一个是 必需的:

FilePathField.path
必要的。The absolute filesystem path to a directory from which this FilePathField should get its choices. 例如: "_home_images".

FilePathField.match
可选的.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.

Of course, these arguments can be used together.

有一点需要提醒的是 match只匹配基本文件名(base filename), 而不是整个文件路径(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

class FloatField([options])
用Python的一个float 实例来表示一个浮点数.

该字段的默认组件是一个 TextInput.

FloatField vs. DecimalField

有时候FloatField 类会和DecimalField 类发生混淆. 虽然它们表示都表示实数,但是二者表示数字的方式不一样。FloatField 使用的是Python内部的 float 类型, 而DecimalField 使用的是Python的 Decimal 类型. 想要了解更多二者的差别, 可以查看Python文档中的 decimal 模块.

ImageField

class ImageField([upload_to=None, height_field=None, width_field=None, max_length=100, options])

继承了 FileField的所有属性和方法, 但还对上传的对象进行校验,确保它是个有效的image.

除了从FileField继承来的属性外,ImageField 还有宽和 高属性。

为了更便捷的去用那些属性值, ImageField 有两个额外的可选参数

ImageField.height_field¶
该属性的设定会在模型实例保存时,自动填充图片的高度.

ImageField.width_field¶
该属性的设定会在模型实例保存时,自动填充图片的宽度.

ImageField字段需要调用Pillow 库.

ImageField会创建在你的数据库中 和 varchar 一样,默认最大长度为100和其他字段一样, 你可以使用max_length 参数来设置默认文件最大值.

The default form widget for this field is a ClearableFileInput.

IntegerField

class IntegerField([options])

一个整数。在Django所支持的所有数据库中,从 -2147483648 到 2147483647 范围内的值是合法的。默认的表单输入工具是TextInput.

GenericIPAddressField

class GenericIPAddressField([protocol=both, unpack_ipv4=False, options])¶

和 IPv4 or IPv6 地址, in string format (e.g. 192.0.2.30 or 2a02:42fe::4). 这个字段的默认表单小部件是一个TextInput.

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

class NullBooleanField([options])
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(正整数字段)

class PositiveIntegerField([options])¶
类似 IntegerField, 但值必须是正数或者零(0). Values from 0 to 2147483647 are safe in all databases supported by Django. The value 0 is accepted for backward compatibility reasons.

PositiveSmallIntegerField¶

class PositiveSmallIntegerField([options])¶
该模型字段类似 PositiveIntegerField, 但是只允许小于某一特定值(依据数据库类型而定)。从0 到 32767 这个区间,对于Django所支持的所有数据库而言都是安全的。

SlugField

class SlugField([max_length=50, options])¶
Slug 是一个新闻术语(通常叫做短标题)。一个slug只能包含字母、数字、下划线或者是连字符,通常用来作为短标签。通常它们是用来放在URL里的。

与CharField类似, 你可以指定 max_length 的值(read the note about database portability and max_length in that section, too). 如果没有指定 max_length, Django将会默认长度为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.

SmallIntegerField

class SmallIntegerField([options])

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

class TextField([options])

巨大的文本域.该模型默认的表单组件是Textarea。

如果在TextField指定max_length属性,将影响到的是Textarea插件,但是不会强制模型或者数据库级别。如果需要限制的话最好使用CharField

TimeField

class TimeField([auto_now=False, auto_now_add=False, options])¶
时间字段,和Python中 datetime.time 一样。Accepts the same auto-population options as DateField.

表单默认为 TextInput.输入框。The admin adds some JavaScript shortcuts.

URLField

class URLField([max_length=200, options])

一个CharField 类型的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

New in Django 1.8.
class UUIDField([options])¶
一个用来存储UUID的字段。使用Python的UUID类。 当使用PostgreSQL数据库时,该字段类型对应的数据库中的数据类型是uuid,使用其他数据库时,数据库对应的是char(32)类型。

使用UUID类型相对于使用具有primary_key参数的AutoField类型是一个更好的解决方案。 数据库不会自动生成UUID,所以推荐使用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

注意:这里使用了一个方法(省略了括号),而不是使用一个UUID的实例给default参数赋值。