## 模型入門 本章節簡要概述了模型定義,和一些重要的欄位、和欄位參數。 ### 模型定義 模型通常在 app 中的 `models.py` 檔案中定義。它們是繼承自 django.db.models.Model的子類別,可以包括屬性,方法和描述性資料(metadata)。以下的程式碼片段是一個名為MyModelName的「典型」模型範例碼: ```python= from django.db import models class MyModelName(models.Model): """A typical class defining a model, derived from the Model class.""" # Fields my_field_name = models.CharField(max_length=20, help_text='Enter field documentation') ... # Metadata class Meta: ordering = ['-my_field_name'] # Methods def get_absolute_url(self): """Returns the url to access a particular instance of MyModelName.""" return reverse('model-detail-view', args=[str(self.id)]) def __str__(self): """String for representing the MyModelName object (in Admin site etc.).""" return self.field_name ``` 在下面章節中,我們將詳細解釋模型的每個功能。 ### 欄位(Field) 模型可以有任意數量的欄位、任何類型的欄位 — 每一個欄位都代表我們要儲存在資料庫資料表中的一欄資料(a column of data)。每一筆資料庫記錄(列 row)會由每個欄位的數值組成。接著我們來看看上面的例子: ```python my_field_name = models.CharField(max_length=20, help_text='Enter field documentation') ``` 在上面例子中,有個叫 `my_field_name` 的單一欄位,其類型為 models.CharField — 這意味著這個欄位將會包含字母、數字字串。透過特定的類別(specific classes)可指定欄位的類型(Field types),這些類別(classes)會決定這筆紀錄將使用哪一種類型的資料儲存在資料庫中,以及從 HTML 表單接收到值(即構成有效值)時使用的驗證標準。欄位類型還可以獲取參數,進一步指定欄位如何儲存或如何被使用。在這個範例中,我們給了欄位兩個參數:
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up