Python網頁設計-Django使用筆記(五):資料庫(CRUD)
Django系列文:
Python網頁設計-Django使用筆記(二):實作104職缺爬蟲APP
Python網頁設計-Django使用筆記(三):Mezzanine CMS
Python網頁設計-Django使用筆記(四):LINE聊天機器人(部署至Heroku)
Python網頁設計-Django使用筆記(五):資料庫(CRUD)
如果讀者還不知道CRUD是什麼,可以先參考維基百科:
在Django使用資料庫有5個重要步驟:
- 在model.py中定義class類別,每一個類別相當於一個資料表
- 在class類別中定義變數,每一個變數相當於一個資料表欄位
- 用「python manage.py makemigrations」建立資料庫和Django間的中介檔
- 用「python manage.py migrate」同步更新資料庫內容
- 在Python程式中存取資料庫(CRUD)
假設我們已建立了一個students專案,裡面有studentsapp應用程式、templates和static資料夾、makemigrations資料檔,並利用migrate將模型與資料庫同步,同時也完成settings.py的設定,views.py的功能也撰寫完成。
定義資料模型
students\urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from studentsapp import viewsurlpatterns = [
path('admin/', admin.site.urls),
url(r'^listone/$', views.listone),
url(r'^listall/$', views.listall),
url(r'^insert/$', views.insert),
url(r'^modify/$', views.modify),
url(r'^delete/$', views.delete),
]
建立資料模型
studentsapp\models.py
在class類別中定義變數,每一個變數相當於一個資料表欄位
from django.db import modelsclass student(models.Model):
cName = models.CharField(max_length=20, null=False)
cSex = models.CharField(max_length=2, default='M', null=False)
cBirthday = models.DateField(null=False)
cEmail = models.EmailField(max_length=100, blank=True, default='')
cPhone = models.CharField(max_length=50, blank=True, default='')
cAddr = models.CharField(max_length=255,blank=True, default='')
def __str__(self):
return self.cName# max_length代表最大長度20字元
# default='M'代表預設值為M
# null=False代表不可空白
# blank=True代表預設空字串
# editable代表是否可顯示,預設為True
# unique代表是否為唯一值,預設為False
建立migration資料檔
資料庫模型建立完成後,必須將架構和版本記錄下來,以利後續追蹤
用「python manage.py makemigrations」建立資料庫和Django間的中介檔
在命令提示字元輸入以下指令:
python manage.py makemigrations
模型與資料庫同步
用「python manage.py migrate」同步更新資料庫內容
在命令提示字元輸入以下指令:
python manage.py migrate
注意:如果後續還有更改的model.py中的資料定義,必須再建立資料檔並且同步到資料庫
python manage.py makemigrations
python manage.py migrate
admin後臺管理與ModelAdmin類別
admin後臺管理
studentsapp\admin.py
從admin.py中加入student套件
from django.contrib import admin
from studentsapp.models import student# 第三種方式,加入 ModelAdmin 類別,定義顯示欄位、欄位過濾資料、搜尋和排序
class studentAdmin(admin.ModelAdmin):
list_display=('id','cName','cSex','cBirthday','cEmail','cPhone','cAddr')
list_filter=('cName','cSex')
search_fields=('cName',)
ordering=('id',)
admin.site.register(student,studentAdmin)
建立管理員帳號與密碼
python manage.py createsuperuser
啟動伺服器
python manage.py runserver#到瀏覽器輸入127.0.0.1:8000/admin/,輸入帳號和密碼進入Django的管理後台。其中的Students是我們剛才在admin.py當中註冊的廖表
新增資料
可在網站介面下進行新增
定義ModelAdmin類別
顯示多個欄位
#使用list_display顯示多個欄位list_display=('id','cName','cSex','cBirthday','cEmail','cPhone','cAddr')#使用list_filter資料過濾
list_filter=('cName','cSex')#使用search_fields依照欄位搜尋
search_fields=('cName',)#使用ordering排序
ordering=('id',)
#ordering=('-id',) 遞減排序
資料庫查詢
objects.get()取得一筆資料(R)
studentsapp\views.py
from django.shortcuts import render
from studentsapp.models import studentdef listone(request):
try:
unit = student.objects.get(cName="李采茜") #讀取一筆資料
except:
errormessage = " (讀取錯誤!)"
return render(request, "listone.html", locals())
listone.html
<!DOCTYPE html>
<html>
<head>
<title>顯示一筆資料</title>
</head>
<body>
<h2>顯示 student 資料表一筆資料{{errormessage}}</h2>
編號:{{ unit.id }} <br />
姓名:{{ unit.cName }} <br />
性別:{{ unit.cSex }} <br />
生日:{{ unit.cBirthday}} <br />
郵件帳號:{{unit.cEmail }} <br />
電話:{{ unit.cPhone }} <br />
地址:{{ unit.cAddr}} <br />
</body>
</html>
objects.all()取得所有資料(R)
studentsapp\views.py
from django.shortcuts import render
from studentsapp.models import studentdef listall(request):
students = student.objects.all().order_by('id')
#讀取資料表, 依 id 遞增排序(欄位前加入負號-id代表遞減排序)
return render(request, "listall.html", locals())
listall.html
<!DOCTYPE html>
<html>
<head>
<title>顯示所有資料</title>
</head>
<body>
<h2>顯示 student 資料表所有資料</h2>
<table border="1" cellpadding="0" cellspacing="0">
<th>編號</th><th>姓名</th><th>性別</th><th>生日</th>
<th>郵件帳號</th><th>電話</th><th>地址</th>
{% for student in students %}
<tr>
<td>{{ student.id }} </td>
<td>{{ student.cName }} </td>
<td>{{ student.cSex}} </td>
<td>{{ student.cBirthday }} </td>
<td>{{ student.cEmail }} </td>
<td>{{ student.cPhone}} </td>
<td>{{ student.cAddr }} </td>
</tr>
{% endfor %}
</table>
</body>
</html>
資料庫管理
students\urls.py
加入資料管理的連結到urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from studentsapp import viewsurlpatterns = [
path('admin/', admin.site.urls),
url(r'^listone/$', views.listone),
url(r'^listall/$', views.listall), url(r'^insert/$', views.insert), #新增資料
url(r'^modify/$', views.modify), #修改資料
url(r'^delete/$', views.delete), #刪除資料
]
新增資料(C)
studentsapp\views.py
def insert(request): #新增資料
cName = '林三和'
cSex = 'M'
cBirthday = '1987-12-26'
cEmail = 'bear@superstar.com'
cPhone = '0963245612'
cAddr = '台北市信義路18號'
unit = student.objects.create(cName=cName, cSex=cSex, cBirthday=cBirthday, cEmail=cEmail,cPhone=cPhone, cAddr=cAddr)
unit.save() #寫入資料庫
students = student.objects.all().order_by('-id') #讀取資料表, 依 id 遞減排序
return render(request, "listall.html", locals())
瀏覽結果
http://127.0.0.1:8000/insert/
修改資料(U)
修改資料第一步先取得資料(student.objects.get()),接著逐一設定要修改的欄位值
def modify(request): #修改資料
unit = student.objects.get(cName='林三和')
unit.cBirthday = '1987-12-11'
unit.cAddr = '台北市信義路234號'
unit.save() #寫入資料庫
students = student.objects.all().order_by('-id')
return render(request, "listall.html", locals())
瀏覽結果
http://127.0.0.1:8000/modify/
刪除資料(D)
與修改資料時相同,第一步是取得資料(student.objects.get()),接著執行unit.delete()方法來刪除資料
def delete(request,id=None): #刪除資料
unit = student.objects.get(cName='林三和')
unit.delete()
students = student.objects.all().order_by('-id')
return render(request, "listall.html", locals())
瀏覽結果
http://127.0.0.1:8000/delete/