Djano建立資料庫及表資料
阿新 • • 發佈:2021-09-16
Django資料庫
1,資料庫檔案
在Django專案中,資料庫檔案通常儲存在db.sqlite3檔案中,若專案中沒有則在終端執行python manage.py migrate,專案中就會出現此檔案。
2,下載和連線資料庫
2.1下載sqlite資料庫,https://sqlitestudio.pl/
2.2連線資料庫
下載之後解壓就可以使用。首先點選add database新增一個數據庫,然後選擇sqlite3,檔案則選擇專案中的db.sqlite檔案,然後給資料庫取一個名字,與專案同名最好,之後便將專案的資料庫新增好了,可在sqlite中檢視資料庫結構。
3,建立表結構
3.1表結構所在目錄
通常每一個app都有相對應的資料庫表,在專案中建立一個app,只需在終端執行,python manage.py startapp appname,表結構在app所在的models.py中
3.2models.py程式碼編寫
首先匯入models包
from django.db import models
然後定義資料庫表
class Customer(models.Model): # 客戶名稱 name = models.CharField(max_length=200) # 聯絡電話 phonenumber = models.CharField(max_length=200,default='') # 地址 address = models.CharField(max_length=200,default='')
這個 Customer 類繼承自 django.db.models.Model, 就是用來定義資料庫表的。裡面的 name、phonenumber、address 是該表的3個欄位。