model field 類型1、AutoField 一個自增的IntegerField,一般不直接使用,Django會自動給每張表添加一個自增的primary key。2、BigIntegerField 64位整數, -9223372036854775808 到 922337203685477580 ...
model field 類型
1、AutoField
一個自增的IntegerField,一般不直接使用,Django會自動給每張表添加一個自增的primary key。
2、BigIntegerField
64位整數, -9223372036854775808 到 9223372036854775807。預設的顯示widget 是 TextInput.
3、BinaryField ( Django 1.6 版本新增 )
存儲二進位數據。不能使用 filter 函數獲得 QuerySet
4、BooleanField
True/False,預設的widget 是 CheckboxInput。
如果需要置空,則必須用 NullBooleanField 代替。
Django 1.6 修改:BooleanField 的預設值 由 False 改為 None,在 default 屬性未設置的情況下。
5、CharField
存儲字元串。必須有 max_length 參數指定長度。預設的form widget 是 TextInput
如果字元串巨長,推薦使用 TextField。
6、CommaSeparatedIntegerField
一串由逗號分開的整數。必須有 max_length 參數。
7、DateField
日期,與python里的datetime.date 實例同。有以下幾個可選的選項,均為bool類型:
DateField.auto_now: 每次執行 save 操作的時候自動記錄當前時間,常作為最近一次修改的時間 使用。註意:總是在執行save 操作的時候執行,無法覆蓋。
DateField.auto_now_add: 第一次創建的時候添加當前時間。常作為 創建時間 使用。註意:每次create 都會調用。
預設的form widget 是 TextInput。
註意:設置auto_now 或者 auto_now_add 為 True 會導致當前自動擁有 editable=False 和 blank = True 設置。
8、DateTimeField
日期+時間。與python里的 datetime.datetime 實例同。常用附加選項和DateField一樣。
預設 form widget 是一個 TextInput
9、DecimalField
設置了精度的十進位數字。
A fixed-precision decimal number, represented in Python by a Decimal instance. Has two required arguments:
DecimalField.max_digits
The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places.
DecimalField.decimal_places?
The number of decimal places to store with the number.
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 TextInput.
10、EmailField
在 CharField 基礎上附加了 郵件地址合法性驗證。不需要強制設定 max_length
註意:當前預設設置 max_length 是 75,雖然已經不符合標準,但未了向前相容,未修改。
11、FileField
文件上傳。不支持 primary_key 和 unique 選項。否則會報 TypeError 異常。
必須設置 FileField.upload_to 選項,這個是 本地文件系統路徑,附加在 MEDIA_ROOT 設置的後邊,也就是 MEDIA_ROOT 下的子目錄相對路徑。
預設的form widget 是 FileInput。
使用 FileField 和 ImageField 需要以下步驟:
(1)修改 settting.py,設置 MEDIA_ROOT(使用絕對路徑),指定用戶上傳的文件保存在哪裡。設置 MEDIA_URL,作為 web地址 首碼,要保證 MEDIA_ROOT 目錄對運行 Django 的用戶是可寫的;
(2)在 model 中增加 FileField 或 ImageField,並指定 upload_to 選項指定存在 MEDIA_ROOT 的哪個子目錄里;
(3)存在資料庫里的是什麼東西呢?是 File 或 Image相對於 MEDIA_ROOT 的相對路徑,你可以在 Django 里方便的使用這個地址,比如你的 ImageField 叫 tupian,你可以在 template 中用{{object.tupian.url}}。
舉個例子:假設你的 MEDIA_ROOT='/home/media',upload_to 設置為 'photos/%Y/%m/%d','%Y/%m/%d' 部分使用strftime() 提供。如果你在 2013年10月10日上傳了一個文件,那麼它就存在 /home/media/photos/2013/10/10/ 下。
文件在 model實例 執行 save操作的同時保存,所以文件在model實例執行save之前,硬碟的上的文件名的是不可靠的。
註意:要驗證用戶上傳的文件確實是自己需要的,以防止安全漏洞出現。
預設情況下,FileField 在資料庫中表現為 varchar(100) 的一個列。你可以使用 max_length 來改變這個大小。
11、FileField 和 FieldFile
當你訪問 一個 model 內的 FileField 時,將得到一個 FieldFile 實例來訪問實際的文件。這個類提供了幾個屬性和方法用來和實際的文件數據交互:
FieldFile.url:只讀屬性,獲取文件的相對URL地址;
FieldFile.open( mode = 'rb' ):打開文件,和python 的 open 一樣;
FieldFile.close():和 python 的 file.close() 一樣;
FieldFile.save( name, content, save=True ):name 是文件名,content 是包含了文件內容的 django.core.files.File 實例,與 python 的 file 不一樣。The optional save argument controls whether or not the instance is saved after the file has been altered. Defaults to True。
兩種方式 進行 content 設置:
from django.core.files import File
f = open( 'helo.txt' )
content = File(f)
另一種是:
from django.core.files.base import ContentFile
content = ContentFile( 'helloworld' )
更多內容可見:https://docs.djangoproject.com/en/dev/topics/files/
FieldFile.delete( save = True ):刪除當前的文件。如果文件已經打開,則自動關閉。The optional save argument controls whether or not the instance is saved after the file has been deleted. Defaults to True.
值得註意的是:當一個 model實例 被刪除之後,相關聯的文件並沒有被刪除,需要自己清除!
12、FloatField
與 python 里的 float 實例相同,預設的 form widget 是 TextInput。
雖然 FloatField 與 DecimalField 都是表示實數,但卻是不同的表現形式,FloatField 用的是 python d float 類型,但是 DecimalField 用的卻是 Decimal 類型。區別可見:http://docs.python.org/2.7/library/decimal.html#decimal
13、ImageField
在 FileField 基礎上加上是否是合法圖片驗證功能的一個類型。
除了 FileField 有的屬性外,ImageField 另有 height 和 width 屬性。
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.
註意:需要安裝 PIL 或者 Pillow 模塊。在資料庫中同樣表現為 varchar(100),可通過 max_length 改大小。
14、IntegerField
整數,預設的form widget 是 TextInput。
15、IPAddressField
IP地址,字元串類型,如 127.0.0.1。預設 form widget 是 TextInput。
16、TextField
大文本,巨長的文本。預設的 form widget 是 Textarea。
註意,如果使用 MySQLdb 1.2.1p2 和 utf-8_bin 編碼,會有一些問題https://docs.djangoproject.com/en/dev/ref/databases/#mysql-collation。具體問題未分析,可自行避開。
17、URLField
加了 URL 合法性驗證的 CharField。
預設的 form widget 是 TextInput。
預設max_length=200,可修改。
18、ForeignKey / ManyToManyField / OneToOneField / SmallIntegerField / SlugField / PositiveSmallIntegerField / PositiveIntegerField
Field 選項
null
boolean 值,預設設置為false。通常不將其用於字元型欄位上,比如CharField,TextField上。字元型欄位如果沒有值會返回空字元串。
blank
boolean 值,該欄位是否可以為空。如果為假,則必須有值。
choices
元組值,一個用來選擇值的2維元組。第一個值是實際存儲的值,第二個用來方便進行選擇。如SEX_CHOICES=((‘F’,’Female’),(‘M’,’Male’),)
db_column
string 值,指定當前列在資料庫中的名字,不設置,將自動採用model欄位名;
db_index
boolean 值,如果為True將為此欄位創建索引;
default
給當前欄位設定的預設值,可以是一個具體值,也可以是一個可調用的對象,如果是可調用的對象將每次產生一個新的對象;
editable
boolean 值,如果為假,admin模式下將不能改寫。預設為真;
error_messages
字典,設置預設的出錯信息,可覆蓋的key 有 null, blank, invalid, invalid_choice, 和 unique。
help_text
admin模式下幫助文檔
form widget 內顯示幫助文本。
primary_key
設置主鍵,如果沒有設置django創建表時會自動加上:id = meta.AutoField(‘ID’, primary_key=True)
primary_key=True implies blank=False, null=False and unique=True. Only one primary key is allowed on an object.
radio_admin
用於 admin 模式下將 select 轉換為 radio 顯示。只用於 ForeignKey 或者設置了choices
unique
boolean值,數據是否進行唯一性驗證;
unique_for_date
字元串類型,值指向一個DateTimeField 或者 一個 DateField的列名稱。日期唯一,如下例中系統將不允許title和pub_date兩個都相同的數據重覆出現
title = meta.CharField( maxlength=30, unique_for_date=’pub_date’ )
unique_for_month / unique_for_year
用法同上
verbose_name
string類型。更人性化的列名。
validators
有效性檢查。無效則拋出 django.core.validators.ValidationError 異常。
如何實現檢查器 見:https://docs.djangoproject.com/en/dev/ref/validators/