from djano.db import models #數據庫操做API位置 class Reporter(models.Model): full_name = models.CharField(max_length=70) #print(obj)時輸出對象的full_name def __str__(self): return self.full_name class Article(models.Model): pub_date = models.DateField() headline = models.CharField(max_length=200) content = models.TextField() #注意!!! reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) #外鍵 def __str__(self): return self.headline
用Django命令行工具自動構建database tables。php
python manage.py makemigrations python manage.py migrate
Notes:html
因爲英語水平有限,我看官方3.0文檔同時結合了一1.18版本的中文翻譯文本,在這一步中其執行的是:python
python manage.py syncdb
可見在後續版本中棄用。我猜想由一步分爲兩步的緣由是:爲了不用戶誤操做web
The API is created on the fly, no code generation necessary:正則表達式
這個API是自動生成的,不須要代碼生成:shell
# Import the models we created from our "news" app >>> from news.models import Article, Reporter # No reporters are in the system yet. >>> Reporter.objects.all() <QuerySet []> # Create a new Reporter. >>> r = Reporter(full_name='John Smith') # Save the object into the database. You have to call save() explicitly. >>> r.save() #基於對象的建立數據須要特別調用save方法。 # Now it has an ID. >>> r.id 1 # Now the new reporter is in the database. >>> Reporter.objects.all() <QuerySet [<Reporter: John Smith>]> # Fields are represented as attributes on the Python object. #字段被表示成一個屬性在Python對象中。 >>> r.full_name 'John Smith' # Django provides a rich database lookup API. >>> Reporter.objects.get(id=1) <Reporter: John Smith> >>> Reporter.objects.get(full_name__startswith='John') #基於雙下劃線的模糊查詢。 <Reporter: John Smith> >>> Reporter.objects.get(full_name__contains='mith') <Reporter: John Smith> >>> Reporter.objects.get(id=2) Traceback (most recent call last): ... DoesNotExist: Reporter matching query does not exist. # Create an article. >>> from datetime import date #注意了,官方使用datetime庫來操做時間而不是time >>> a = Article(pub_date=date.today(), headline='Django is cool', ... content='Yeah.', reporter=r) #外鍵增長的方法之一。 >>> a.save() #基於對象建立的必定要調用save方法提交。猜想是就是調用COMMIT。 # Now the article is in the database. >>> Article.objects.all() <QuerySet [<Article: Django is cool>]> # Article objects get API access to related Reporter objects. >>> r = a.reporter >>> r.full_name 'John Smith' # And vice versa: Reporter objects get API access to Article objects. >>> r.article_set.all() #反向查詢。 <QuerySet [<Article: Django is cool>]> # The API follows relationships as far as you need, performing efficient # JOINs for you behind the scenes. # This finds all articles by a reporter whose name starts with "John". >>> Article.objects.filter(reporter__full_name__startswith='John') #基於雙下劃綫的正向查詢。 <QuerySet [<Article: Django is cool>]> # Change an object by altering its attributes and calling save(). >>> r.full_name = 'Billy Goat' # update >>> r.save() # Delete an object with delete(). >>> r.delete() #delete
admin 它不單單是一個腳手架!! 它是整個房子。數據庫
Once your models are defined, Django can automatically create a professional, production ready administrative interface– a website that lets authenticated users add, change and delete objects. The only step required is to register your model in the admin site:express
from django.db import models #操做數據庫API位置 #記得繼承models模塊下的Model類 class Article(models.Model): pub_date = models.DateField() headline = models.CharField(max_length=200) content = models.TextField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
from django.contrib import admin #admin的位置 from . import models admin.site.register(models.Article) #註冊須要管理的字段
The philosophy here is that your site is edited by a staff, or a client, or maybe just you – and you don’t want to have to deal with creating backend interfaces only to manage content.django
One typical workflow in creating Django apps is to create models and get the admin sites up and running as fast as possible, so your staff (or clients) can start populating data. Then, develop the way data is presented to the public.api
一般一個網站會有你的員工,客戶或者只有你來編輯,但你可能並不想所以而去建立一個後臺管理系統。
在一個建立Django應用的典型工做流中,首先須要建立模型並儘量快地啓動和運行admin sites,讓你的員工(或者客戶)可以開始錄入數據。而後,纔開始展示數據給公衆的方式。
A clean, elegant URL scheme is an important detail in a high-quality Web application. Django encourages beautiful URL design and doesn’t put any cruft in URLs, like .php
or .asp
.
To design URLs for an app, you create a Python module called a URLconf. A table of contents for your app, it contains a mapping between URL patterns and Python callback functions. URLconfs also serve to decouple URLs from Python code.
from django.urls import path from . import views urlpatterns = [ path('articles/<int:year>/', views.year_archive), path('articles/<int:year>/<int:month>/', views.month_archive), path('articles/<int:year>/<int:month>/<int:pk>/', views.article_detail), ]
The code above maps URL paths to Python callback functions (「views」). The path strings use parameter tags to 「capture」 values from the URLs. When a user requests a page, Django runs through each path, in order, and stops at the first one that matches the requested URL. (If none of them matches, Django calls a special-case 404 view.) This is blazingly fast, because the paths are compiled into regular expressions at load time.
Once one of the URL patterns matches, Django calls the given view, which is a Python function. Each view gets passed a request object – which contains request metadata – and the values captured in the pattern.
For example, if a user requested the URL 「/articles/2005/05/39323/」, Django would call the function news.views.article_detail(request, year=2005, month=5, pk=39323)
.
相似於<int:year>是一個過濾器,會在URLs中捕捉匹配的值。當一個用戶發出請求是,Django會按照順序去匹配每個模式,並停在第一個匹配請求的URL上。(若是沒有匹配到,那麼Django會返回404頁面),這個過程是很是快的,由於加載時正則表達式已經在加載時編譯好了。
Each view is responsible for doing one of two things: Returning an HttpResponse
object containing the content for the requested page, or raising an exception such as Http404
. The rest is up to you.
Generally, a view retrieves data according to the parameters, loads a template and renders the template with the retrieved data. Here’s an example view for year_archive
from above:
from django.shortcuts import render #render函數在這裏哦,之後記住位置哦,shortcuts,回憶:admin在contrib裏,models在db裏,path在urls中。 from .models import Article def year_archive(request, year): a_list = Article.objects.filter(pub_date__year=year) context = {'year': year, 'article_list': a_list} #傳給模板系統渲染頁面。 return render(request, 'news/year_archive.html', context)
This example uses Django’s template system, which has several powerful features but strives to stay simple enough for non-programmers to use.
The code above loads the news/year_archive.html
template.
Django has a template search path, which allows you to minimize redundancy among templates. In your Django settings, you specify a list of directories to check for templates with DIRS
. If a template doesn’t exist in the first directory, it checks the second, and so on.
Let’s say the news/year_archive.html
template was found. Here’s what that might look like:
{% extends "base.html" %} {% block title %}Articles for {{ year }}{% endblock %} {% block content %} <h1>Articles for {{ year }}</h1> {% for article in article_list %} <p>{{ article.headline }}</p> <p>By {{ article.reporter.full_name }}</p> <p>Published {{ article.pub_date|date:"F j, Y" }}</p> {% endfor %} {% endblock %}
在Django設置中,你能夠指定一個查找模板的目錄列表。若是一個模板沒有在這個列表中,則會去找第二個。
Variables are surrounded by double-curly braces. {{ article.headline }}
means 「Output the value of the article’s headline attribute.」 But dots aren’t used only for attribute lookup. They also can do dictionary-key lookup, index lookup and function calls.
Note {{ article.pub_date|date:"F j, Y" }}
uses a Unix-style 「pipe」 (the 「|」 character). This is called a template filter, and it’s a way to filter the value of a variable. In this case, the date filter formats a Python datetime object in the given format (as found in PHP’s date function).
You can chain together as many filters as you’d like. You can write custom template filters. You can write custom template tags, which run custom Python code behind the scenes.
Finally, Django uses the concept of 「template inheritance」. That’s what the {% extends "base.html" %}
does. It means 「First load the template called ‘base’, which has defined a bunch of blocks, and fill the blocks with the following blocks.」 In short, that lets you dramatically cut down on redundancy in templates: each template has to define only what’s unique to that template.
Here’s what the 「base.html」 template, including the use of static files, might look like:
{% load static %} <html> <head> <title>{% block title %}{% endblock %}</title> </head> <body> <img src="{% static "images/sitelogo.png" %}" alt="Logo"> {% block content %}{% endblock %} </body> </html>
Simplistically, it defines the look-and-feel of the site (with the site’s logo), and provides 「holes」 for child templates to fill. This means that a site redesign can be done by changing a single file – the base template.
It also lets you create multiple versions of a site, with different base templates, while reusing child templates. Django’s creators have used this technique to create strikingly different mobile versions of sites by only creating a new base template.
Note that you don’t have to use Django’s template system if you prefer another system. While Django’s template system is particularly well-integrated with Django’s model layer, nothing forces you to use it. For that matter, you don’t have to use Django’s database API, either. You can use another database abstraction layer, you can read XML files, you can read files off disk, or anything you want. Each piece of Django – models, views, templates – is decoupled from the next.
Django的建立者已經利用這個技術來創造了顯著不一樣的手機版本的網站,只須要建立一個新的基礎模板
This has been only a quick overview of Django’s functionality. Some more useful features:
The next steps are for you to download Django, read the tutorial and join the community. Thanks for your interest!
database-schema 數據庫架構 technical specifics 技術細節 object-relational-mapper 對象映射表 access 訪問 With that 接着 on the fly 動態 be created on the fly 被動動態生成 explictly /ɪkˈsplɪsɪtli/ 明確的,明白的 vice 惡習,缺點,賣淫 vice versa 反之亦然 behind the scenes 幕後 interface 接口,界面 scaffolding 腳手架 RMB:SCAF利人利己的-self centred altruism fad production ready 生產可用性(可用於生產環境的) administrative 管理的 administrative interface 管理界面 professional, production ready administrative interface. 專業的,可用於生產環境的管理界面。 contrib 普通發佈版,軟件庫 philosophy 設計理念,哲學 RMB: 飛人(phi)跟我囉嗦(loso)哲學(philosophy)我氣飛了(phy) workflow 工做流 typical 典型的 populating data 展示數據 get up 啓動 elegant 優雅的 RMB: 螞蟻(ant)帶上個(g)面具(ele),非常優雅(elegant) scheme 計劃,策劃,方案 blazingly 強烈的,超級無敵的 blazing 燃燒的,耀眼的,炙熱的,激烈的,情感強烈的 blaze 燃燒,發光,宣揚 The rest is up to you. 剩下的就靠你了 be up to 依靠於... retrieve 檢索,取回 RMB: 不斷地(re)在樹(tree)中檢索(retrieve)字母i和v。 redundancy 冗餘 re dun dancy RMB: 阿姨(re)燉(dun)蛋(dan)和草魚(cy),這養分有點冗餘(redundancy)啊 decouple 解耦 de couple RMB: 得嘞(de), 一對夫妻(couple)又被王默默拆散了(解耦) serve to 有助於 double-curly braces 雙花括號 curly adj.