migrations文件夾
1. 如何解決Django 1.8在migrate時失敗
1. 創建項目
運行下面命令就可以創建一個 django 項目,項目名稱叫 mysite :
$ django-admin.py startproject mysite
創建後的項目目錄如下:
mysite
├── manage.py
└── mysite
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
1 directory, 5 files
說明:
__init__.py :讓 python 把該目錄當成一個開發包 (即一組模塊)所需的文件。 這是一個空文件,一般你不需要修改它。
manage.py :一種命令行工具,允許你以多種方式與該 Django 項目進行交互。 鍵入python manage.py help,看一下它能做什麼。 你應當不需要編輯這個文件;在這個目錄下生成它純是為了方便。
settings.py :該 Django 項目的設置或配置。
urls.py:Django項目的URL路由設置。目前,它是空的。
wsgi.py:WSGI web 應用伺服器的配置文件。更多細節,查看 How to deploy with WSGI
接下來,你可以修改 settings.py 文件,例如:修改 LANGUAGE_CODE、設置時區 TIME_ZONE
SITE_ID = 1
LANGUAGE_CODE = 'zh_CN'
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = True
上面開啟了 [Time zone](https://docs.djangoproject.com/en/1.7/topics/i18n/timezones/) 特性,需要安裝 pytz:
$ sudo pip install pytz
2. 運行項目
在運行項目之前,我們需要創建資料庫和表結構,這里我使用的默認資料庫:
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, contenttypes, auth, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying sessions.0001_initial... OK
然後啟動服務:
$ python manage.py runserver
你會看到下面的輸出:
Performing system checks...
System check identified no issues (0 silenced).
January 28, 2015 - 02:08:33
Django version 1.7.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
這將會在埠8000啟動一個本地伺服器, 並且只能從你的這台電腦連接和訪問。 既然伺服器已經運行起來了,現在用網頁瀏覽器訪問 http://127.0.0.1:8000/。你應該可以看到一個令人賞心悅目的淡藍色 Django 歡迎頁面它開始工作了。
你也可以指定啟動埠:
$ python manage.py runserver 8080
以及指定 ip:
$ python manage.py runserver 0.0.0.0:8000
3. 創建 app
前面創建了一個項目並且成功運行,現在來創建一個 app,一個 app 相當於項目的一個子模塊。
在項目目錄下創建一個 app:
$ python manage.py startapp polls
如果操作成功,你會在 mysite 文件夾下看到已經多了一個叫 polls 的文件夾,目錄結構如下:
polls
├── __init__.py
├── admin.py
├── migrations
│ └── __init__.py
├── models.py
├── tests.py
└── views.py
1 directory, 6 files
4. 創建模型
每一個 Django Model 都繼承自 django.db.models.Model
在 Model 當中每一個屬性 attribute 都代表一個 database field
通過 Django Model API 可以執行資料庫的增刪改查, 而不需要寫一些資料庫的查詢語句
打開 polls 文件夾下的 models.py 文件。創建兩個模型:
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
然後在 mysite/settings.py 中修改 INSTALLED_APPS 添加 polls:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
在添加了新的 app 之後,我們需要運行下面命令告訴 Django 你的模型做了改變,需要遷移資料庫:
$ python manage.py makemigrations polls
你會看到下面的輸出日誌:
Migrations for 'polls':
0001_initial.py:
- Create model Choice
- Create model Question
- Add field question to choice
你可以從 polls/migrations/0001_initial.py 查看遷移語句。
運行下面語句,你可以查看遷移的 sql 語句:
$ python manage.py sqlmigrate polls 0001
輸出結果:
BEGIN;
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);
CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
CREATE TABLE "polls_choice__new" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id"));
INSERT INTO "polls_choice__new" ("choice_text", "votes", "id") SELECT "choice_text", "votes", "id" FROM "polls_choice";
DROP TABLE "polls_choice";
ALTER TABLE "polls_choice__new" RENAME TO "polls_choice";
CREATE INDEX polls_choice_7aa0f6ee ON "polls_choice" ("question_id");
COMMIT;
你可以運行下面命令,來檢查資料庫是否有問題:
$ python manage.py check
再次運行下面的命令,來創建新添加的模型:
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, contenttypes, polls, auth, sessions
Running migrations:
Applying polls.0001_initial... OK
總結一下,當修改一個模型時,需要做以下幾個步驟:
修改 models.py 文件
運行 python manage.py makemigrations 創建遷移語句
運行 python manage.py migrate,將模型的改變遷移到資料庫中
你可以閱讀 django-admin.py documentation,查看更多 manage.py 的用法。
創建了模型之後,我們可以通過 Django 提供的 API 來做測試。運行下面命令可以進入到 python shell 的交互模式:
$ python manage.py shell
下面是一些測試:
>>> from polls.models import Question, Choice # Import the model classes we just wrote.
# No questions are in the system yet.
>>> Question.objects.all()
[]
# Create a new Question.
# Support for time zones is enabled in the default settings file, so
# Django expects a datetime with tzinfo for pub_date. Use timezone.now()
# instead of datetime.datetime.now() and it will do the right thing.
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
# Save the object into the database. You have to call save() explicitly.
>>> q.save()
# Now it has an ID. Note that this might say "1L" instead of "1", depending
# on which database you're using. That's no biggie; it just means your
# database backend prefers to return integers as Python long integer
# objects.
>>> q.id
1
# Access model field values via Python attributes.
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
# Change values by changing the attributes, then calling save().
>>> q.question_text = "What's up?"
>>> q.save()
# objects.all() displays all the questions in the database.
>>> Question.objects.all()
[<Question: Question object>]
列印所有的 Question 時,輸出的結果是 [<Question: Question object>],我們可以修改模型類,使其輸出更為易懂的描述。修改模型類:
from django.db import models
class Question(models.Model):
# ...
def __str__(self): # __unicode__ on Python 2
return self.question_text
class Choice(models.Model):
# ...
def __str__(self): # __unicode__ on Python 2
return self.choice_text
接下來繼續測試:
>>> from polls.models import Question, Choice
# Make sure our __str__() addition worked.
>>> Question.objects.all()
[<Question: What's up?>]
# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
[<Question: What's up?>]
>>> Question.objects.filter(question_text__startswith='What')
[<Question: What's up?>]
# Get the question that was published this year.
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>
# Request an ID that doesn't exist, this will raise an exception.
>>> Question.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Question matching query does not exist.
# Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Question.objects.get(id=1).
>>> Question.objects.get(pk=1)
<Question: What's up?>
# Make sure our custom method worked.
>>> q = Question.objects.get(pk=1)
# Give the Question a couple of Choices. The create call constructs a new
# Choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object. Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a question's choice) which can be accessed via the API.
>>> q = Question.objects.get(pk=1)
# Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
[]
# Create three choices.
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
# Choice objects have API access to their related Question objects.
>>> c.question
<Question: What's up?>
# And vice versa: Question objects get access to Choice objects.
>>> q.choice_set.all()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> q.choice_set.count()
3
# The API automatically follows relationships as far as you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want; there's no limit.
# Find all Choices for any question whose pub_date is in this year
# (reusing the 'current_year' variable we created above).
>>> Choice.objects.filter(question__pub_date__year=current_year)
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
# Let's delete one of the choices. Use delete() for that.
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()
>>>
上面這部分測試,涉及到 django orm 相關的知識,詳細說明可以參考 Django中的ORM。
5. 管理 admin
Django有一個優秀的特性, 內置了Django admin後台管理界面, 方便管理者進行添加和刪除網站的內容.
新建的項目系統已經為我們設置好了後台管理功能,見 mysite/settings.py:
INSTALLED_APPS = (
'django.contrib.admin', #默認添加後台管理功能
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mysite',
)
同時也已經添加了進入後台管理的 url, 可以在 mysite/urls.py 中查看:
url(r'^admin/', include(admin.site.urls)), #可以使用設置好的url進入網站後台
接下來我們需要創建一個管理用戶來登錄 admin 後台管理界面:
$ python manage.py createsuperuser
Username (leave blank to use 'june'): admin
Email address:
Password:
Password (again):
Superuser created successfully.
總結
最後,來看項目目錄結構:
mysite
├── db.sqlite3
├── manage.py
├── mysite
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
├── polls
│ ├── __init__.py
│ ├── admin.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── __init__.py
│ ├── models.py
│ ├── templates
│ │ └── polls
│ │ ├── detail.html
│ │ ├── index.html
│ │ └── results.html
│ ├── tests.py
│ ├── urls.py
│ ├── views.py
└── templates
└── admin
└── base_site.htm
2. 來自資料庫的codefirst 怎麼用
如果你還在為
支持xxx上下文的模型已在資料庫創建後發生更改。請考慮使用 Code First 遷移更新資料庫
找到你的資料庫上下文所在的類庫(一般都是寫在項目中的model中,也有的獨立model類庫)
打開Nuget 程序包管理控制台
輸入:Enable-Migrations 回車
如果正確的話 則顯示已為項目 xxx啟用 Code First 遷移。
我在這里說下 幾種有可能出現的錯誤:
1.No context type was found in the assembly xxx
在當前項目中 沒有找到資料庫上下文,也就是DbContext 繼承的的 "資料庫.cs"
2.The EntityFramework package is not installed on project xxx
當前項目已經找到了數據上下文,但是沒有EntityFrameWork 需要安裝輸入 install-package entityframework(手大的 不知道對不對)
基本就這兩個問題,如果安裝成功則在項目中 出現Migrations文件夾,裡面會記錄每次數據遷移所發生的變化。
非常好用,不用再刪除資料庫 重新生成 數據丟失等問題。
常用語句 :enable-Migrations -Force 替換遷移數據文件 update-database 更新 add-migration 添加新的更新文件
求採納為滿意回答
3. laravel 控制器在哪個文件夾
根目錄/app/http/Controllers
laravel目錄結構:
註:寫本文時參照的是5.1.4版本
目錄或文件 說明
|–app 包含Controller、Model、路由等在內的應用目錄,大部分業務將在該目錄下進行
||–Console 命令行程序目錄
|||–Commands 包含了用於命令行執行的類,可在該目錄下自定義類
|||–Kernel.php 命令調用內核文件,包含commands變數(命令清單,自定義的命令需加入到這里)和schele方法(用於任務調度,即定時任務)
||–Events 事件目錄
||–Exceptions 包含了自定義錯誤和異常處理類
||–Http HTTP傳輸層相關的類目錄
|||–Controllers 控制器目錄
|||–Kernel.php 包含http中間件和路由中間件的內核文件
|||–Middleware 中間件目錄
|||–Requests 請求類目錄
|||–routes.php 強大的路由
||–Jobs 該目錄下包含隊列的任務類
||–Listeners 監聽器目錄
||–Providers 服務提供者目錄
||–User.php 自帶的模型實例,我們新建的Model默認也存儲在該目錄
|–artisan 強大的命令行介面,你可以在app/Console/Commands下編寫自定義命令
|–bootstrap 框架啟動載入目錄
||–app.php 創建框架應用實例
||–autoload.php 自動載入
||–cache 存放框架啟動緩存,web伺服器需要有該目錄的寫入許可權
|–composer.json 存放依賴關系的文件
|–composer.lock 鎖文件,存放安裝時依賴包的真實版本
|–config 各種配置文件的目錄
||–app.php 系統級配置文件
||–auth.php 用戶身份認證配置文件,指定好table和model就可以很方便地用身份認證功能了
||–broadcasting.php 事件廣播配置文件
||–cache.php 緩存配置文件
||–compile.php 編譯額外文件和類需要的配置文件,一般用戶很少用到
||–database.php 資料庫配置文件
||–filesystems.php 文件系統配置文件,這里可以配置雲存儲參數
||–mail.php 電子郵件配置文件
||–queue.php 消息隊列配置文件
||–services.php 可存放第三方服務的配置信息
||–session.php 配置session的存儲方式、生命周期等信息
||–view.php 模板文件配置文件,包含模板目錄和編譯目錄等
|–database 資料庫相關目錄
||–factories 5.1版本的新特性,工廠類目錄,也是用於數據填充
|||–ModelFactory.php 在該文件可定義不同Model所需填充的數據類型
||–migrations 存儲資料庫遷移文件
||–seeds 存放數據填充類的目錄
||–DatabaseSeeder.php 執行php artisan db:seed命令將會調用該類的run方法。該方法可調用執行該目錄下其他Seeder類,也可調用factories方法生成ModelFactory里定義的數據模型
|–.env 環境配置文件。config目錄下的配置文件會使用該文件裡面的參數,不同生產環境使用不同的.env文件即可。
|–gulpfile.js gulp(一種前端構建工具)配置文件
|–package.json gulp配置文件
|–phpspec.yml phpspec(一種PHP測試框架)配置文件
|–phpunit.xml phpunit(一種PHP測試框架)配置文件
|–public 網站入口,應當將ip或域名指向該目錄而不是根目錄。可供外部訪問的css、js和圖片等資源皆放置於此
||–index.php 入口文件
||–.htaccess Apache伺服器用該文件重寫URL
||–web.config IIS伺服器用該文件重寫URL
|–resources 資源文件目錄
||–assets 可存放包含LESS、SASS、CoffeeScript在內的原始資源文件
||–lang 本地化文件目錄
||–views 視圖文件就放在這啦
|–server.php PHP內置的Web伺服器將把這個文件作為入口。以public/index.php為入口的可以忽略掉該文件
|–storage 存儲目錄。web伺服器需要有該目錄及所有子目錄的寫入許可權
||–app 可用於存儲應用程序所需的一些文件?待補充
||–framework 該目錄下包括緩存、sessions和編譯後的視圖文件
||–logs 日誌目錄
|–tests 測試目錄
|–vendor 該目錄下包含Laravel源代碼和第三方依賴包
4. django項目 makemigrations時出現django.db.migrations.graph.nodenotfounderror錯誤。
1. 創建項目
運行下面命令就可以創建一個 django 項目,項目名稱叫 mysite :
$ django-admin.py startproject mysite
創建後的項目目錄如下:
mysite
├── manage.py
└── mysite
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
1 directory, 5 files
說明:
__init__.py :讓 Python 把該目錄當成一個開發包 (即一組模塊)所需的文件。 這是一個空文件,一般你不需要修改它。
manage.py :一種命令行工具,允許你以多種方式與該 Django 項目進行交互。 鍵入python manage.py help,看一下它能做什麼。 你應當不需要編輯這個文件;在這個目錄下生成它純是為了方便。
settings.py :該 Django 項目的設置或配置。
urls.py:Django項目的URL路由設置。目前,它是空的。
wsgi.py:WSGI web 應用伺服器的配置文件。更多細節,查看 How to deploy with WSGI
接下來,你可以修改 settings.py 文件,例如:修改 LANGUAGE_CODE、設置時區 TIME_ZONE
SITE_ID = 1
LANGUAGE_CODE = 'zh_CN'
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = True
上面開啟了 [Time zone]() 特性,需要安裝 pytz:
$ sudo pip install pytz
2. 運行項目
在運行項目之前,我們需要創建資料庫和表結構,這里我使用的默認資料庫:
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, contenttypes, auth, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying sessions.0001_initial... OK
然後啟動服務:
$ python manage.py runserver
你會看到下面的輸出:
Performing system checks...
System check identified no issues (0 silenced).
January 28, 2015 - 02:08:33
Django version 1.7.1, using settings 'mysite.settings'
Starting development server at
Quit the server with CONTROL-C.
這將會在埠8000啟動一個本地伺服器, 並且只能從你的這台電腦連接和訪問。 既然伺服器已經運行起來了,現在用網頁瀏覽器訪問 。你應該可以看到一個令人賞心悅目的淡藍色 Django 歡迎頁面它開始工作了。
你也可以指定啟動埠:
$ python manage.py runserver 8080
以及指定 ip:
$ python manage.py runserver 0.0.0.0:8000
3. 創建 app
前面創建了一個項目並且成功運行,現在來創建一個 app,一個 app 相當於項目的一個子模塊。
在項目目錄下創建一個 app:
$ python manage.py startapp polls
如果操作成功,你會在 mysite 文件夾下看到已經多了一個叫 polls 的文件夾,目錄結構如下:
polls
├── __init__.py
├── admin.py
├── migrations
│ └── __init__.py
├── models.py
├── tests.py
└── views.py
1 directory, 6 files
4. 創建模型
每一個 Django Model 都繼承自 django.db.models.Model
在 Model 當中每一個屬性 attribute 都代表一個 database field
通過 Django Model API 可以執行資料庫的增刪改查, 而不需要寫一些資料庫的查詢語句
打開 polls 文件夾下的 models.py 文件。創建兩個模型:
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
然後在 mysite/settings.py 中修改 INSTALLED_APPS 添加 polls:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
在添加了新的 app 之後,我們需要運行下面命令告訴 Django 你的模型做了改變,需要遷移資料庫:
$ python manage.py makemigrations polls
你會看到下面的輸出日誌:
Migrations for 'polls':
0001_initial.py:
- Create model Choice
- Create model Question
- Add field question to choice
你可以從 polls/migrations/0001_initial.py 查看遷移語句。
運行下面語句,你可以查看遷移的 sql 語句:
$ python manage.py sqlmigrate polls 0001
輸出結果:
BEGIN;
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);
CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
CREATE TABLE "polls_choice__new" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id"));
INSERT INTO "polls_choice__new" ("choice_text", "votes", "id") SELECT "choice_text", "votes", "id" FROM "polls_choice";
DROP TABLE "polls_choice";
ALTER TABLE "polls_choice__new" RENAME TO "polls_choice";
CREATE INDEX polls_choice_7aa0f6ee ON "polls_choice" ("question_id");
COMMIT;
你可以運行下面命令,來檢查資料庫是否有問題:
$ python manage.py check
再次運行下面的命令,來創建新添加的模型:
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, contenttypes, polls, auth, sessions
Running migrations:
Applying polls.0001_initial... OK
總結一下,當修改一個模型時,需要做以下幾個步驟:
修改 models.py 文件
運行 python manage.py makemigrations 創建遷移語句
運行 python manage.py migrate,將模型的改變遷移到資料庫中
你可以閱讀 django-admin.py documentation,查看更多 manage.py 的用法。
創建了模型之後,我們可以通過 Django 提供的 API 來做測試。運行下面命令可以進入到 python shell 的交互模式:
$ python manage.py shell
下面是一些測試:
>>> from polls.models import Question, Choice # Import the model classes we just wrote.
# No questions are in the system yet.
>>> Question.objects.all()
[]
# Create a new Question.
# Support for time zones is enabled in the default settings file, so
# Django expects a datetime with tzinfo for pub_date. Use timezone.now()
# instead of datetime.datetime.now() and it will do the right thing.
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
# Save the object into the database. You have to call save() explicitly.
>>> q.save()
# Now it has an ID. Note that this might say "1L" instead of "1", depending
# on which database you're using. That's no biggie; it just means your
# database backend prefers to return integers as Python long integer
# objects.
>>> q.id
1
# Access model field values via Python attributes.
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
# Change values by changing the attributes, then calling save().
>>> q.question_text = "What's up?"
>>> q.save()
# objects.all() displays all the questions in the database.
>>> Question.objects.all()
[<Question: Question object>]
列印所有的 Question 時,輸出的結果是 [<Question: Question object>],我們可以修改模型類,使其輸出更為易懂的描述。修改模型類:
from django.db import models
class Question(models.Model):
# ...
def __str__(self): # __unicode__ on Python 2
return self.question_text
class Choice(models.Model):
# ...
def __str__(self): # __unicode__ on Python 2
return self.choice_text
接下來繼續測試:
>>> from polls.models import Question, Choice
# Make sure our __str__() addition worked.
>>> Question.objects.all()
[<Question: What's up?>]
# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
[<Question: What's up?>]
>>> Question.objects.filter(question_text__startswith='What')
[<Question: What's up?>]
# Get the question that was published this year.
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>
# Request an ID that doesn't exist, this will raise an exception.
>>> Question.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Question matching query does not exist.
# Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Question.objects.get(id=1).
>>> Question.objects.get(pk=1)
<Question: What's up?>
# Make sure our custom method worked.
>>> q = Question.objects.get(pk=1)
# Give the Question a couple of Choices. The create call constructs a new
# Choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object. Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a question's choice) which can be accessed via the API.
>>> q = Question.objects.get(pk=1)
# Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
[]
# Create three choices.
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
# Choice objects have API access to their related Question objects.
>>> c.question
<Question: What's up?>
# And vice versa: Question objects get access to Choice objects.
>>> q.choice_set.all()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> q.choice_set.count()
3
# The API automatically follows relationships as far as you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want; there's no limit.
# Find all Choices for any question whose pub_date is in this year
# (reusing the 'current_year' variable we created above).
>>> Choice.objects.filter(question__pub_date__year=current_year)
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
# Let's delete one of the choices. Use delete() for that.
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()
>>>
上面這部分測試,涉及到 django orm 相關的知識,詳細說明可以參考 Django中的ORM。
5. 管理 admin
Django有一個優秀的特性, 內置了Django admin後台管理界面, 方便管理者進行添加和刪除網站的內容.
新建的項目系統已經為我們設置好了後台管理功能,見 mysite/settings.py:
INSTALLED_APPS = (
'django.contrib.admin', #默認添加後台管理功能
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mysite',
)
同時也已經添加了進入後台管理的 url, 可以在 mysite/urls.py 中查看:
url(r'^admin/', include(admin.site.urls)), #可以使用設置好的url進入網站後台
接下來我們需要創建一個管理用戶來登錄 admin 後台管理界面:
$ python manage.py createsuperuser
Username (leave blank to use 'june'): admin
Email address:
Password:
Password (again):
Superuser created successfully.
總結
最後,來看項目目錄結構:
mysite
├── db.sqlite3
├── manage.py
├── mysite
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
├── polls
│ ├── __init__.py
│ ├── admin.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── __init__.py
│ ├── models.py
│ ├── templates
│ │ └── polls
│ │ ├── detail.html
│ │ ├── index.html
│ │ └── results.html
│ ├── tests.py
│ ├── urls.py
│ ├── views.py
└── templates
└── admin
└── base_site.htm
通過上面的介紹,對 django 的安裝、運行以及如何創建視 圖和模型有了一個清晰的認識,接下來就可以深入的學習 django 的自動化測試、持久化、中間件、國 際 化等知識。
5. C盤migration內文件
是微軟拼音輸入法,如果你不用微軟拼音的話可以禁用,可以在輸入法那塊兒右擊,設置,把微軟拼音輸入法刪了就不會有了