Django快速入門-數(shù)據(jù)庫(kù)模型

Django快速入門-數(shù)據(jù)庫(kù)模型詳細(xì)操作教程

本系列教程第一部分已經(jīng)講完了。在上一個(gè)教程的基礎(chǔ)上,在這一講中我們將建立數(shù)據(jù)庫(kù),創(chuàng)建第一個(gè)模型,并使用一個(gè) Django 快速自動(dòng)生成的管理站點(diǎn)。

數(shù)據(jù)庫(kù)配置

現(xiàn)在,打開mysite/settings.py。Django設(shè)置模塊級(jí)的變量與正常的Python模塊一樣。

默認(rèn)情況下,配置使用SQLite。如果你是數(shù)據(jù)庫(kù)新手,或者想嘗試學(xué)習(xí)Django,這是最簡(jiǎn)單的選擇。SQLite包含在Python,所以不需要安裝任何東西來(lái)支持你的數(shù)據(jù)庫(kù)。當(dāng)開始你的第一個(gè)真正的項(xiàng)目,可能需要使用更強(qiáng)大的數(shù)據(jù)庫(kù)如:PostgreSQL,MySQL等,可以配置數(shù)據(jù)庫(kù)切換就可以了。

如果你想使用其他數(shù)據(jù)庫(kù),請(qǐng)安裝相應(yīng)的數(shù)據(jù)庫(kù)綁定,并更改以下鍵在數(shù)據(jù)庫(kù)中“默認(rèn)”的配置項(xiàng),以適合您的數(shù)據(jù)庫(kù)連接設(shè)置:

ENGINE – 輸入'django.db.backends.sqlite3', 'django.db.backends.postgresql','django.db.backends.mysql',或'django.db.backends.oracle' NAME – 數(shù)據(jù)庫(kù)的名稱。如果使用SQLite,數(shù)據(jù)庫(kù)會(huì)在您的計(jì)算機(jī)上創(chuàng)建文件;在這種情況下,名稱應(yīng)該是完整的絕對(duì)路徑的文件,包括文件名。默認(rèn)值為 os.path.join(BASE_DIR,“db.sqlite3”),將存儲(chǔ)在您的項(xiàng)目目錄中的文件。

如果你不使用SQLite作為數(shù)據(jù)庫(kù),而使用其他設(shè)置,如USER, PASSWORD, 和 HOST 必須加入。欲了解更多詳細(xì)信息,請(qǐng)參閱用于 數(shù)據(jù)庫(kù)的參考文檔。

當(dāng)你編輯 mysite/settings.py,時(shí)區(qū)設(shè)置TIME_ZONE。

此外,請(qǐng)注意,在該文件的頂部的 INSTALLED_APPS 設(shè)置。它包含了很多在本Django示例中激活的所有 Django 的應(yīng)用程序的名稱。 應(yīng)用程序可以在多個(gè)項(xiàng)目中使用,你可以打包給別人并在他們的項(xiàng)目分發(fā)使用。

默認(rèn)情況下,INSTALLED_APPS包含以下內(nèi)容的應(yīng)用程序,這些都使用 Django :

django.contrib.admin – 管理站點(diǎn),這里會(huì)很快使用它 django.contrib.auth – 認(rèn)證系統(tǒng) django.contrib.contenttypes – 一個(gè)框架,內(nèi)容類型 django.contrib.sessions – 會(huì)話框架 django.contrib.messages – 消息傳遞框架 django.contrib.staticfiles – 一個(gè)框架用來(lái)管理靜態(tài)文件

這些應(yīng)用包括默認(rèn),作為一個(gè)方便常見的實(shí)例。

其中的一些應(yīng)用程序使用至少一個(gè)數(shù)據(jù)庫(kù)表,所以我們需要在數(shù)據(jù)庫(kù)中創(chuàng)建的表才可以使用它們。要做到這一點(diǎn),運(yùn)行以下命令:

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
C:\Python27\mysite>python manage.py migrate
 Operations to perform:
   Apply all migrations: admin, contenttypes, auth, sessions
 Running migrations:
   Rendering model states... DONE
   Applying contenttypes.0001_initial... OK
   Applying auth.0001_initial... OK
   Applying admin.0001_initial... OK
   Applying admin.0002_logentry_remove_auto_add... OK
   Applying contenttypes.0002_remove_content_type_name... OK
   Applying auth.0002_alter_permission_name_max_length... OK
   Applying auth.0003_alter_user_email_max_length... OK
   Applying auth.0004_alter_user_username_opts... OK
   Applying auth.0005_alter_user_last_login_null... OK
   Applying auth.0006_require_contenttypes_0002... OK
   Applying auth.0007_alter_validators_add_error_messages... OK
   Applying sessions.0001_initial... OK
 C:\Python27\mysite>

migrate 命令著眼于INSTALLED_APPS設(shè)置并創(chuàng)建根據(jù)您的 mysite/settings.py 文件數(shù)據(jù)庫(kù)設(shè)置,并隨應(yīng)用程序數(shù)據(jù)庫(kù)遷移任何數(shù)據(jù)庫(kù)表(我們將在以后的教程討論)。你會(huì)看到每個(gè)適用移植的消息。 如果有興趣,運(yùn)行命令行在你的數(shù)據(jù)庫(kù)客戶端,列如類型\dt (PostgreSQL), SHOW TABLES; (MySQL), .schema (SQLite), 或 SELECT TABLE_NAME FROMUSER_TABLES; (Oracle) 以顯示Django所創(chuàng)建的表。

創(chuàng)建模型

現(xiàn)在,我們將定義模型 - 本質(zhì)上數(shù)據(jù)庫(kù)進(jìn)行設(shè)計(jì),使用其他元數(shù)據(jù)。

在我們的簡(jiǎn)單調(diào)查的應(yīng)用程序,我們將創(chuàng)建兩個(gè)模型:Question 和 Choice。Question有一個(gè)問(wèn)題標(biāo)題和發(fā)布日期。Choice有兩個(gè)字段:選擇文本和票數(shù)。每個(gè)選項(xiàng)都與一個(gè)問(wèn)題關(guān)聯(lián)。

這些概念由簡(jiǎn)單的Python類來(lái)表示。編輯 polls/models.py 文件,所以  polls/models.py 看起來(lái)是這樣的:


 # Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
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)

該代碼是直接的。每個(gè)模型是django.db.models.Model類的子類。 每個(gè)模型具有許多類變量,每一個(gè)在模型變量與數(shù)據(jù)庫(kù)表的字段關(guān)聯(lián)。

每個(gè)字段由 Field 類實(shí)例表示 – 例如,CharField表示字符型字段,DateTimeField表示日期時(shí)間字段。這告訴Django 每個(gè)字段保存的數(shù)據(jù)類型。

每個(gè)Field實(shí)例(例如,question_text或pub_date)的名稱是字段的名稱,這是機(jī)器友好的格式。在Python代碼中使用這個(gè)值,數(shù)據(jù)庫(kù)將使用它作為列名。

字段也可以有不同的可選參數(shù);在本示例中,我們已經(jīng)將票數(shù)的默認(rèn)值設(shè)置為0。

最后,需要注意的是關(guān)系的定義,這里使用了外鍵。這告訴 Django 每個(gè)選項(xiàng)關(guān)聯(lián)一個(gè)問(wèn)題。 Django支持所有常見的數(shù)據(jù)庫(kù)關(guān)系:多對(duì)一,多對(duì)多以及一對(duì)之一。

激活模型

模型代碼很小,但表示了 Django 的很多信息。有了它 Django 可以:

為這個(gè)應(yīng)用程序創(chuàng)建數(shù)據(jù)庫(kù)(CREATE TABLE語(yǔ)句)

創(chuàng)建訪問(wèn) Question 和 Choice對(duì)象的Python數(shù)據(jù)庫(kù)訪問(wèn)API

但首先我們需要告訴 polls 項(xiàng)安裝了的應(yīng)用程序。

再次編輯 mysite/settings.py 文件,并更改INSTALLED_APPS設(shè)置包含字符串“polls.apps.PollsConfig”。結(jié)果如下所示:

mysite/settings.py文件內(nèi)容如下:

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
現(xiàn)在Django知道 polls 投票程序。讓我們運(yùn)行另一個(gè)命令:
# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
C:\Python27\mysite>python manage.py makemigrations polls
 Migrations for 'polls':
   0001_initial.py:
     - Create model Choice
     - Create model Question
     - Add field question to choice
 C:\Python27\mysite>

通過(guò)運(yùn)行makemigrations,告訴Django你已經(jīng)做了模型一些改動(dòng)(在這種情況下,已經(jīng)是最新的了),并且你想更改存儲(chǔ)作為一個(gè)移植。

遷移是Django怎么存儲(chǔ)您更改的模型(由你的數(shù)據(jù)庫(kù)架構(gòu)決定)- 它們只是在磁盤上的文件。您如果喜歡可以讀取移植新的模型,它在文件 polls/migrations/0001_initial.py。你不會(huì)希望Django每一次都讀取它們,不過(guò)將它們?cè)O(shè)計(jì)成人可編輯的,你要知道Django是如何變化的并手動(dòng)調(diào)整。

還有將運(yùn)行migrations,自動(dòng)管理數(shù)據(jù)庫(kù)模式(表)命令 - 這就是所謂的遷移,讓我們看看SQL了解移植運(yùn)行。 sqlmigrate 命令將移植名稱返回SQL顯示:


 # Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
$ python manage.py sqlmigrate polls 0001

應(yīng)該看到類似下面的東西(我們已經(jīng)重新格式化它的可讀性):

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
C:\Python27\mysite>python manage.py sqlmigrate polls 0001
 BEGIN;
 --
 -- Create model Choice
 --
 CREATE TABLE "polls_choice" ("id" integer not NULL PRIMARY KEY AUTOINCREMENT, "c
 hoice_text" varchar(200) not NULL, "votes" integer not NULL);
 --
 -- Create model Question
 --
 CREATE TABLE "polls_question" ("id" integer not NULL PRIMARY KEY AUTOINCREMENT,
 "question_text" varchar(200) not NULL, "pub_date" datetime not NULL);
 --
 -- Add field question to choice
 --
 ALTER TABLE "polls_choice" RENAME TO "polls_choice__old";
 CREATE TABLE "polls_choice" ("id" integer not NULL PRIMARY KEY AUTOINCREMENT, "c
 hoice_text" varchar(200) not NULL, "votes" integer not NULL, "question_id" integ
 er not NULL REFERENCES "polls_question" ("id"));
 INSERT INTO "polls_choice" ("choice_text", "votes", "id", "question_id") SELECT
 "choice_text", "votes", "id", NULL from "polls_choice__old";
 DROP TABLE "polls_choice__old";
 CREATE INDEX "polls_choice_7aa0f6ee" ON "polls_choice" ("question_id");
 COMMIT;
 C:\Python27\mysite>

遷移命令將所有還沒有被應(yīng)用的遷移(Django跟蹤哪些是使用數(shù)據(jù)庫(kù)中的一個(gè)特殊的表名為django_migrations應(yīng)用)運(yùn)行它們?cè)跀?shù)據(jù)庫(kù)中 - 基本上是,將使用模型在數(shù)據(jù)庫(kù)模式的變化同步。

使用API

現(xiàn)在,讓我們進(jìn)入交互式 Python shell  和 Django 所提供的API 。要調(diào)用Python命令行,請(qǐng)使用以下命令:

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
C:\Python27\mysite>python manage.py shell
 Python 2.7.10 (default, May 23 2015, 09:44:00) [MSC v.1500 64 bit (AMD64)] on wi
 n32
 Type "help", "copyright", "credits" or "license" for more information.
 (InteractiveConsole)
 >>>

只需鍵入“python” 來(lái)代替,因?yàn)閙anage.py設(shè)置DJANGO_SETTINGS_MODULE環(huán)境變量,這給Django Python 導(dǎo)入路徑到 mysite/settings.py文件。

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
>>> import django
 >>> django.setup()
# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
>>> 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>]

這里需要等待一會(huì)兒. <Question: Question object>完全是這個(gè)對(duì)象的無(wú)用表示。讓我們來(lái)解決這個(gè)問(wèn)題:通過(guò)編輯Question模型(在polls/models.py 文件),并添加一個(gè)__str__() 方法到這兩個(gè)Question 和 Choice 模型:

polls/models.py文件內(nèi)容如下:
 # Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
from django.db import models
 from django.utils.encoding import python_2_unicode_compatible
 @python_2_unicode_compatible # only if you need to support Python 2
 class Question(models.Model):
     # ...
     def __str__(self):
         return self.question_text
 @python_2_unicode_compatible # only if you need to support Python 2
 class Choice(models.Model):
     # ...
     def __str__(self):
         return self.choice_text

添加 __str__() 方法是非常重要的,使用交互式提示處理添加到模型中,不僅為自己方便,也是因?yàn)閷?duì)象的表示用于整個(gè) Django 自動(dòng)生成管理。

注意,這些都是正常的Python方法。讓我們添加一個(gè)自定義的方法,這里只是為了演示:polls/models.py

 # Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
import datetime
 from django.db import models
 from django.utils import timezone
 class Question(models.Model):
     # ...
     def was_published_recently(self):
         return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

注意這里增加 import datetime 和from django.utils import timezon,引用Python的標(biāo)準(zhǔn)的datetime模塊和Django的時(shí)區(qū)相關(guān)的實(shí)用程序在django.utils.timezone,如果不熟悉在Python的時(shí)區(qū)處理,可以閱讀  時(shí)區(qū)支持文檔。

保存這些修改,并再次運(yùn)行 python manage.py shell 啟動(dòng)一個(gè)新的Python交互shell:

 # Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
>>> 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)
 >>> q.was_published_recently()
 True
 # 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管理

創(chuàng)建一個(gè)管理員用戶

首先,我們需要?jiǎng)?chuàng)建可以登錄到管理界面的用戶。運(yùn)行以下命令:

 # Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08c:\python27\mysite> python manage.py createsuperuser

輸入你想要的用戶名(隨便一個(gè)),然后按Enter。

 # Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
Username: admin

然后,將提示輸入電子郵件地址(隨便一個(gè)):

 # Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
Email address: xxx@(cainiaoplus.com)

最后一步是要輸入密碼。它會(huì)要求輸入密碼兩次,第二次為第一的確認(rèn)。

 # Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
Password: **********
 Password (again): *********
 Superuser created successfully.

啟動(dòng)開發(fā)服務(wù)器

Django管理站點(diǎn)默認(rèn)激活。讓我們啟動(dòng)開發(fā)服務(wù)器,并探索它。

如果服務(wù)器未運(yùn)行,啟動(dòng)它,如下所示:

 # Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
c:\python27\mysite>python manage.py runserver

現(xiàn)在,打開Web瀏覽器,進(jìn)入“/admin/” 本地域名- 例如,   http://127.0.0.1:8000/admin/  應(yīng)該看到管理員登錄界面:  瀏覽器運(yùn)行結(jié)果

由于移在默認(rèn)情況下開啟,登錄屏幕可能會(huì)顯示在你自己的語(yǔ)言, 由于翻譯在默認(rèn)情況下開啟,登錄屏幕可能會(huì)顯示在你自己的語(yǔ)言,

輸入管理員網(wǎng)站

現(xiàn)在,嘗試與在上一步中創(chuàng)建的超級(jí)用戶帳號(hào)登錄。應(yīng)該會(huì)看到 Django 管理的首頁(yè):  瀏覽器運(yùn)行結(jié)果

你應(yīng)該看到一些可編輯內(nèi)容:組和用戶。它們由django.contrib.auth,Django的認(rèn)證框架提供。

修改poll 管理程序

poll應(yīng)用程序在哪里?它不會(huì)顯示在管理索引頁(yè)面上。

只有一件事要做:我們需要告訴管理員這個(gè)Question對(duì)象有一個(gè)管理界面。要做到這一點(diǎn),打開 polls/admin.py文件,并修改它如下:  

 # Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
from django.contrib import admin
 from .models import Question
 admin.site.register(Question)

瀏覽管理功能

現(xiàn)在,我們已經(jīng)注冊(cè)Question,Django知道它應(yīng)該在管理主頁(yè)面上顯示:

瀏覽器運(yùn)行結(jié)果

點(diǎn)擊“Questions”?,F(xiàn)在,在“change list”頁(yè)面查看問(wèn)題。該頁(yè)面顯示數(shù)據(jù)庫(kù)中的所有問(wèn)題,并允許您選擇其中一個(gè)進(jìn)行更改。還有我們先前創(chuàng)建的問(wèn)題:

瀏覽器運(yùn)行結(jié)果

點(diǎn)擊“What's new?”這個(gè)問(wèn)題進(jìn)行編輯:

瀏覽器運(yùn)行結(jié)果

需要注意的事項(xiàng)在這里列出:

 

表單是從問(wèn)題(Question)模型自動(dòng)產(chǎn)生。

 

不同型號(hào)的字段類型(DateTimeField,CharField)對(duì)應(yīng)相應(yīng)的HTML輸入部件。每個(gè)字段類型知道自己在Django管理中如何顯示。

每個(gè)DateTimeField字段得到 JavaScript 快捷方式。日期得到一個(gè)“Today”的快捷方式并且彈出日歷,并多次獲得了“Now”快捷方式并彈出窗口,列出了常用的輸入時(shí)間。

修改“Date published”點(diǎn)擊“Today”和“Now”快捷方式。然后點(diǎn)擊“Save and continue editing.”,然后點(diǎn)擊“History”在右上角。你會(huì)看到一個(gè)頁(yè)面,列出通過(guò)Django管理到這個(gè)對(duì)象的所有變化,修改人用戶名和時(shí)間戳:  瀏覽器運(yùn)行結(jié)果 代碼下載:  http://pan.baidu.com/s/1jGR3wDg

丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清