Models and databases
Models
Model 是你的資料中,單一、明確的資料來源,包含兩個要素,(一或多個)根本的 field &被你儲存的資料的 behavior。一個 model 映射一個 table
- 三個基本
- 每個 model 都是 django.db.models.Model 的子類別
- model 的每個屬性都代表著一個資料庫的 field,屬性映射到 table column
- 所以 Django 才能有自動生成,存取資料庫的 API
Using models
model 定義完成後,必須在專案 setting.py
設定 INSTALLED_APPS
, model 才能被使用
Fields
- Django用型別 (類別 Field)來決定:
- column 的型別 (
INTEGER
, VARCHAR
, TEXT
)
- form field 中,預設 HTML 輸入型別 (
<input type="text">
, <select>
)
- 小型驗證需求 (如 admin 或自動生成的 form)
用內部類別 Meta 把 metadata 提供給 model
Model metadata is “anything that’s not a field”
Model attributes
model 最重要的屬性就是 Manager,它是 model 查詢資料庫和從資料庫取回實例的接口 (interface)
Model methods
定義特製方法來操作物件,特製 table 中的 row
Model inheritance
- 在 Django 可能有三種繼承方式:
- 母類別擁有共同資訊,並繼承給子 models
- 繼承現存的 model,model 和子 model 都要有自己的 table
- 只是想要修改 model python-level 的行為,沒有要更動 field
Organizing models in a package
太多 model 的時候,建議組織成套件
Making queries
當 model 創建好時,就能自動使用 Django 的 API 來創造、取回、更新、刪除物件
一個 model 就代表一個資料庫 table,一個類別的實例就代表 table 裡的紀錄
Creating objects
用關鍵字引數 (kwarg) 來實例化,指派給變數儲存 (variable.save()
)
背後使用 SQL INSERT
Save changes to objects
將新的數據值指派給變數(variable.kw =
)
背後使用 SQL UPDATE
Retrieving objects
在類別 model 中透過類別 Manager 建構 QuerySet,才能將物件自資料庫取回
一個 Queryset 代表在資料庫中多個物件的集合, Queryset 可以擁有零到多個 filter, filter 依照參數篩選查詢結果
背後使用 SQL SELECT 表 Queryset,WHERE or LIMIT 表 filter
Deleting objects
Handling HTTP requests
URL dispatcher
Overview
利用創建的 Python 模組 URLconf(URL configuration)來設計應用程式的 URL,這個模組映射 URL 路徑表達到 views 中的 Python 函式
How Django processes a request
server 收到 request 時執行的演算法:
- Django 決定要使用的 ROOT_URLCONF
- Django 讀取 Python 模組,並尋找變數的 urlpatterns
- Django 按順序查找 URL 模式,找到第一個匹配的 URL 模式便停止
- Django 找到 URL 模式後,匯入並呼叫給定的 view (一個 function 或 class-based view),讓 view 得到下列引數
- 一個 HttpRequest 的實例
- If the matched URL pattern returned no named groups, then the matches from the regular expression are provided as positional arguments.
- 若 URL 匹配失敗或是發生例外, Django 使用 error-handling view
Path converters
str, int, slug, uuid, path
Writing views
view function 是 Python function 接收 request 後回傳 response,response 可以是 HTML, redirect, 404 error, XML document, image 等等任何東西
Returning errors
使用 HttpResponse 的子類別來回傳 HTTP 的狀態碼
View decorators
Django 提供很多運用在 view 來支援 HTTP 的 decorator
Allowed HTTP methods
用 decorator 決定管制的 HTTP request method
Conditional viewing processing
File uploads
Basic file uploads
Django shortcut functions
為了方便
- render(request, template_name)
結合給定的 template 和 context dictionary ,回傳 HttpResponse 物件
- redirect()
- get_object_or_404()
- get_list_or_404()
Template
一個 template 包含靜態的 HTML 輸出以及能夠讓動態內容插入的特殊語法
Django 的 template 系統有內建後端,稱為 Django template language (DTL),也有熱門的 jinja2
Django 定義了 API 來讀取和回覆 template,而不是用後端
讀取 (loading):尋找給定 identifier 的 template 並預處理及編譯
回覆 (rendering):將資料插入 template 並回傳結果字串
Supports for template engines
Configuration
Template engines 被配置在 TEMPLATE 中
- 'BACKEND'
- django.template.backends.django.DjangoTemplates
- django.template.backends.jinja2.Jinja2
- 'DIR' 定義 engine 尋找 template 來源檔的目錄清單
Usage
- django.template.loader 模組定義下列函式來讀取模組
- get_template()
讀取 template 並回傳 template object
- select_template()
讓 template 讀取更有彈性
- render_to_string()
同時 load 和 render 的 shortcut
- 如果 template 讀取失敗,django.template.exceptions 舉出例外
The Django template language (DTL)
Syntax
DTL 語法涉及4個構想:
- Variables
Variables are surrounded by {{ and }}
- Tags
Tags 在回覆 (render) 過程中提供任意邏輯
Tags are surrounded by {% and %}
- Filters
轉換 variables 的值或 tags 的引數
look like { django} or { my_date}
- Comments
look like {# this won't be rendered #}
Components
Migrations
在 model 中所做的改作,透過 migration 更新資料庫的大綱
The commands
將 migrations 想成資料庫大綱的版本控制系統
- migrate
啟用 model
- makemigrations
像版控的 commit,將 models 打包成 migration 檔案
- sqlmigrate
- showmigrations
Workflow
先 commit(makemigrations) 再 apply(migrate)
- class-based views 將 views 實作成 python object,與 function-based views 比較會有下列優點:
- 組織關於 HTTP 方法的程式時(如GET, POST, etc.),可以直接針對那個方法,不用繁瑣的使用條件式(conditional branching)
- 運用物件導向中 mixins(multiple inheritance) 的技巧,將程式碼重塑成可以重新使用的(reuseable)部件
- generic views, class-based views, class-based generic views 的歷史與關係