1. 程式人生 > >Django---Models(表的建立)

Django---Models(表的建立)

設定資料庫:

django預設資料庫是自帶的SQLite資料庫,如果改其它資料則在根目錄下settings.py檔案中設定,下圖是MySQL資料庫


每個Model類都需要繼承models.Model

from django.db import models

class ModelTest(models.Model):
    ...

常用欄位:

django所有的資料模型都繼承自models.Model
CharField max_length (輸入框)
TextField 沒有長度限制的字串 (文字域)
DateField 日期
DateTimeField 日期+時間
BooleanField 真假
NullBooleanField Null,真假,
Integer 整數
PositiveIntegerField 正整數
DecimalField max_digits(幾位數) decimal_places(小數點後保留幾位)
ImageField 圖片 依賴於 Pillow(處理圖片) upload_to='upload' 指定檔案上傳到目錄
FileField(ImageField繼承FileField)
AutoField
ForeignKey 1:n
ManyToManyField n:n
EmailField 郵箱
UUIDField 重複的概率非常低基本可以忽略,全世界都不一樣的標示,uuid的產生和伺服器的環境有關(CPU,閘道器,) 唯一性的標示,使用者模組,訂單號
不同的欄位在後臺對應不同的html的元件
ImageField 依賴於Pillow元件(python庫)

常用屬性:
unique 標示這個欄位唯一
default 預設的意思 ,(如果不寫的話就使用預設的值)
null=True 允許欄位為null,(允許資料庫為null)資料庫層面的
blank=True 表單階段的,admin後臺的
auto_now 針對時間的,自動調整當前,(當修改條目的時候,這個時間會自動更新),每次修改都會更新 (修改,儲存的時候才會生效,)
auto_now_add 針對時間的,只新增一次,(建立的時間)

根據model建立表:

    生成遷移檔案:

python manage.py makemigrations 應用名

    根據遷移檔案生成資料庫:

python manage.py migrate

逆向生成(根據資料庫生成model):

python manage.py inspectdb>應用名/models.py

生成過程中失敗問題

  1. 刪除模組下(問題模組)的所有的遷移記錄(migrations目錄中)
  2. 刪除資料庫中django_migrations中問題模組的遷移記錄(在資料庫中找到對應的資料刪除)
  3. 刪除這個模組下已經產生的所有的表
  4. 重新生成遷移檔案
  5. 重新遷移

例子:

class Post(models.Model):
    pid = models.AutoField(primary_key=True)
    title = models.CharField(max_length=30,unique=True,blank=False,null=False)
    content = models.TextField()
    access_count = models.PositiveIntegerField()
    price = models.DecimalField(max_digits=5,decimal_places=2)
    isdelete = models.BooleanField()
    created = models.DateField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    img = models.ImageField(upload_to='upload/images')
    file = models.FileField(upload_to='upload/files')

    class Meta:
        db_table='t_post'    #給資料表取名,預設表名:應用名_類名

    def __unicode__(self):    #輸出格式,django2.x用 def __str__(self):
        return u'Post:%s'%self.title