django 框架模型之models常用的Field,及常見錯誤原因及處理方案。


1. django 模型models 常用字段

        
1、models.AutoField  
  •        自增列 = int(11)
  •        如果沒有的話,默認會生成一個名稱為 id 的列
  •        如果要顯式的自定義一個自增列,必須設置primary_key=True。
 
2、models.CharField  
  •        字符串字段
  •   必須設置max_length參數
 
3、models.BooleanField   
  •        布爾類型=tinyint(1)
  •   不能為空,可添加Blank=True
 
4、models.ComaSeparatedIntegerField  
  •        用逗號分割的數字=varchar
  •   繼承CharField,所以必須 max_lenght 參數
 
5、models.DateField
  •        日期類型 date
  •   DateField.auto_now:保存時自動設置該字段為現在日期,最后修改日期
  •        DateField.auto_now_add:當該對象第一次被創建是自動設置該字段為現在日期,創建日期
 
6、models.DateTimeField  
  •        日期時間類型 datetime
  •   同DateField的參數
 
7、models.Decimal  
  •        十進制小數類型 = decimal
  •        DecimalField.max_digits:數字中允許的最大位數
  •        DecimalField.decimal_places:存儲的十進制位數
 
8、models.EmailField  
  •   一個帶有檢查 Email 合法性的 CharField
 
9、models.FloatField  
  •        浮點類型 = double
 
10、models.IntegerField  
  •        整形
 
11、models.BigIntegerField  
  •        長整形
  •   integer_field_ranges = {
    'SmallIntegerField': (-32768, 32767),
    'IntegerField': (-2147483648, 2147483647),
    'BigIntegerField': (-9223372036854775808, 9223372036854775807),
    'PositiveSmallIntegerField': (0, 32767),
    'PositiveIntegerField': (0, 2147483647),
  }
 
12、models.GenericIPAddressField  
  •         一個帶有檢查 IP地址合法性的 CharField
 
13、models.NullBooleanField  
  •        允許為空的布爾類型
 
14、models.PositiveIntegerFiel  
  •        正整數
 
15、models.PositiveSmallIntegerField  
  •        正smallInteger
 
16、models.SlugField  
  •        減號、下划線、字母、數字
 
17、models.SmallIntegerField  
  •        數字
  •   數據庫中的字段有:tinyint、smallint、int、bigint
 
18、models.TextField  
  •         大文本。默認對應的form標簽是textarea。
 
19、models.TimeField  
  •        時間 HH:MM[:ss[.uuuuuu]]
 
20、models.URLField  
  •         一個帶有URL合法性校驗的CharField。
 
21、models.BinaryField  
  •        二進制
  •        存儲二進制數據。不能使用filter函數獲得QuerySet。
 
22、models.ImageField   
  •        圖片
  •        ImageField.height_field、ImageField.width_field:如果提供這兩個參數,則圖片將按提供的高度和寬度規格保存。
  •        該字段要求 Python Imaging 庫Pillow
  •        會檢查上傳的對象是否是一個合法圖片。
 
23、models.FileField(upload_to=None[, max_length=100, ** options])
  •        文件
  •        FileField.upload_to:一個用於保存上傳文件的本地文件系統路徑,該路徑由 MEDIA_ROOT 中設置
  •        這個字段不能設置primary_key和unique選項.在數據庫中存儲類型是varchar,默認最大長度為100
 
24、models.FilePathField(path=None[, math=None, recursive=False, max_length=100, **options])
  •        FilePathField.path:文件的絕對路徑,必填
  •        FilePathField.match:用於過濾路徑下文件名的正則表達式,該表達式將用在文件名上(不包括路徑)。
  •        FilePathField.recursive:True 或 False,默認為 False,指定是否應包括所有子目錄的路徑。
  •        例如:FilePathField(path="/home/images", match="foo.*", recursive=True)
                         將匹配“/home/images/foo.gif”但不匹配“/home/images/foo/bar.gif”     

  


2. django 模型models 字段常用參數
 
1、null
  •         如果是True,Django會在數據庫中將此字段的值置為NULL,默認值是False
 
2、blank
  •   如果為True時django的 Admin 中添加數據時可允許空值,可以不填。如果為False則必須填。默認是False。
  •        null純粹是與數據庫有關系的。而blank是與頁面必填項驗證有關的
 
3、primary_key = False
  •    主鍵,對AutoField設置主鍵后,就會代替原來的自增 id 列
 
4、auto_now 和 auto_now_add
  •   auto_now   自動創建---無論添加或修改,都是當前操作的時間
  •   auto_now_add  自動創建---永遠是創建時的時間
 
5、choices
  •       一個二維的元組被用作choices,如果這樣定義,Django會select box代替普通的文本框,
  •       並且限定choices的值是元組中的值
  •       GENDER_CHOICE = (
  •             (u'M', u'Male'),
  •             (u'F', u'Female'),
  •       )
  •       gender = models.CharField(max_length=2,choices = GENDER_CHOICE)
 
6、max_length
  •         字段長度
 
7、default
  •         默認值
 
8、verbose_name  
  •        Admin中字段的顯示名稱,如果不設置該參數時,則與屬性名。
 
9、db_column  
  •        數據庫中的字段名稱
 
10、unique=True  
  •       不允許重復
 
11、db_index = True  
  •      數據庫索引
 
12、editable=True  
  •       在Admin里是否可編輯
 
13、error_messages=None  
  •       錯誤提示
 
14、auto_created=False  
  •       自動創建
 
15、help_text  
  •       在Admin中提示幫助信息
 
16、validators=[]
  •          驗證器
 
17、upload-to
  •         文件上傳時的保存上傳文件的目錄

 


models.py
        # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
 
class UserInfo(models.Model):
    userName = models.CharField(max_length=30)  #用戶名
    passWord = models.CharField(max_length=30)  #密碼
    gendle = models.BooleanField()  #性別
    birthday = models.DateField()   #出生日期
    weigth = models.FloatField()    #體重
    heigth = models.IntegerField()  #身高
    email = models.EmailField()     #郵箱
    host = models.GenericIPAddressField()  #IP地址
    introduce = models.TextField()  #個人簡介
    blog = models.URLField()        #博客地址
    photo = models.ImageField()     #照片
    CV = models.FilePathField()     #個人簡歷文件
    createDate = models.DateTimeField()     #帳號申請時間

        執行結果:

                
 

3.常見異常處理
    1) 
               ERRORS:
               web.UserInfo.photo: (fields.E210) Cannot use ImageField because Pillow is not installed.
               HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install Pillow".
 
        原因:       

       這是因為使用了ImageField()字段,該字段是直接在數據庫中存儲圖片的,數據庫中實際存儲時要使用python的Pillow模塊對圖片進行處理后才能存儲進去。因此因需使用pip install Pillow 安裝該模塊即可解決該報錯。
    2)
              ERRORS:
                在執行python manage.py makemigrations 時需要手動選擇處理方法:
                You are trying to add a non-nullable field 'CV' to userinfo without a default; we can't do that (the database                     needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
>>> timezone.now
     原因:        
             這是因為 UserInfo數據表中已經有了"userName"和"passWord" 這兩個字段,當在新增字段時就會出現這種Warning。是由於django框架在生成SQL語句時發現數據表不 為空,擔心新增不為Null的字段添加到該表中時,表中以前的數據行在填充這些字段時需要填充的值不明確,所以才會詢問用戶處理方式。
            選1,則會在已存在行中添加null,選2,則會要求在models.py中添加默認值。
            在models.py中設置默認值的方法:
                            host = models.GenericIPAddressField(default = '127.0.0.1')
 
    3)   行python makemigrations正常,但是執行python migrate 報錯,之后再執行無法生效的處理辦法
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM