在django中寫乙個資料庫驅動的web應用的第一步是定義模型,這是資料庫結構設計和附加的其他元資料。
在投票應用中,將建立question(問題)和choice(選項)兩個模型,question模型包括問題描述和發布時間,choice模型包括選項描述和當前得票數。每個選項屬於乙個問題。
重寫polls\models.py
:
from django.db import models
class
question
(models.model)
: question_text = models.charfield(max_length=
200)
pub_date = models.datetimefield(
'date published'
)class
choice
(models.model)
: question = models.foreignkey(question, on_delete=models.cascade)
choice_text = models.charfield(max_length=
200)
votes = models.integerfield(default=
0)
question_text、pub_date
是欄位名,charfield、datetimefield
是字段資料型別
修改mysite\settings.py
:[,
'django.contrib.admin'
,'django.contrib.auth'
,'django.contrib.contenttypes'
,'django.contrib.sessions'
,'django.contrib.messages'
,'django.contrib.staticfiles',]
為模型的修改生成遷移檔案:
(django-env) d:\django projects\mysite>python manage.py makemigrations polls
migrations for
'polls'
: polls\migrations\0001_initial.py
- create model question
- create model choice
通過執行makemigrations命令,django會檢測對模型的修改並將修改的部分儲存為一次遷移。migrations(遷移)是django對於模型定義(資料庫結構)的變化的儲存形式。
檢視模型修改對應的sql語句:
(django-env) d:\django projects\mysite>python manage.py sqlmigrate polls 0001
---- create model question
--create table `polls_question` (`
id`integer auto_increment not null primary key, `question_text`
varchar(200) not null, `pub_date`
datetime(6) not null);--
-- create model choice
--create table `polls_choice` (`
id`integer auto_increment not null primary key, `choice_text`
varchar(200) not null, `votes`
integer not null, `question_id`
integer not null)
;alter table `polls_choice`
add constraint `polls_choice_question_id_c5b4b260_fk_polls_question_id`
foreign key (
`question_id`
) references `polls_question` (`
id`);
應用資料庫遷移:
(django-env) d:\django projects\mysite>python manage.py migrate
operations to perform:
running migrations:
django 購物系統 建立模型
1.前置準備 er圖 實體關係模型設計 uml類圖 類的設計 2.category模型 3.product模型 4 django常用字段型別 booleanfield charfield textfield datefield datetimefield decimalfield filefield...
Django學習筆記4 建立模型
專案環境搭建好了可以開工了。django規定,如果要使用模型,必須要建立乙個應用。通過 djaong 編寫的每個應用都是由python包組成的,這些包存放在你的python path 中並且遵循一定的命名規範。django 提供了個實用工具可以自動生成乙個應用的基本目錄架構,因此你可以專注於編寫 而...
Django筆記 day 2 建立模型
建立表單 models 可提供多種字段 定義部落格型別類,繼承model基類 from django.db import models from django.contrib.auth.models import user class blogtype models.model 部落格型別 mode...