02 - 看一眼Django都有啥
Django是源自於fast-paced newsroom environment
因此Django的目的就是為了使得web開發變得簡單有效
下面的內容是一個用Django開發的a database-driven Web app
1 設計你的模型
你可以使用沒有數據庫的Django
但是如果使用數據庫的話, 由於Django提供了ORM( object-relational mapper )這個能解決很多數據庫問題的數據模型
你可以
mysite/news/models.py
from django.db import models class Reporter(models.Model): full_name = models.CharField(max_length=70) def __str__(self): # __unicode__ on Python 2 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): # __unicode__ on Python 2 return self.headline
2 根據這個模型創建數據庫表
python manage.py migrate
該命令執行的時候, 會查看所有可用的模型, 然後在數據庫中創建相應不存在的表和optionally providing much richer schema control
3 使用Python代碼操作數據庫
1) 導入
from news.models import Reporter, Article
2) 查詢所有內容, 返回的是QuerySet對象, 處理類似於集合的處理方式
表名.onjects.all() >>> Reporter.objects.all() <QuerySet [<Reporter: John Smith>]>
查詢指定列用get()
傳入的參數是一個表達式, 可以使用特殊__startswith, __contains來獲取以開始, 包含
>>> 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>
添加條件過濾用filter()
>>> Article.objects.filter(reporter__full_name__startswith=‘John‘)
<QuerySet [<Article: Django is cool>]>
3) 新增數據
# Create a new Reporter.
>>> r = Reporter(full_name=‘John Smith‘)
# Save the object into the database. You have to call save() explicitly.
>>> r.save()
# Now it has an ID.
>>> r.id
1
>>> from datetime import date
>>> a = Article(pub_date=date.today(), headline=‘Django is cool‘,
... content=‘Yeah.‘, reporter=r)
>>> a.save()
# Article objects get API access to related Reporter objects.
>>> r = a.reporter
>>> r.full_name
‘John Smith‘
4) 刪除數據
# Delete an object with delete().
>>> r.delete()
對Repoter表的操作
1 # Import the models we created from our "news" app
2 >>> from news.models import Reporter, Article
3
4 # No reporters are in the system yet.
5 >>> Reporter.objects.all()
6 <QuerySet []>
7
8 # Create a new Reporter.
9 >>> r = Reporter(full_name=‘John Smith‘)
10
11 # Save the object into the database. You have to call save() explicitly.
12 >>> r.save()
13
14 # Now it has an ID.
15 >>> r.id
16 1
17
18 # Now the new reporter is in the database.
19 >>> Reporter.objects.all()
20 <QuerySet [<Reporter: John Smith>]>
21
22 # Fields are represented as attributes on the Python object.
23 >>> r.full_name
24 ‘John Smith‘
25
26 # Django provides a rich database lookup API.
27 >>> Reporter.objects.get(id=1)
28 <Reporter: John Smith>
29 >>> Reporter.objects.get(full_name__startswith=‘John‘)
30 <Reporter: John Smith>
31 >>> Reporter.objects.get(full_name__contains=‘mith‘)
32 <Reporter: John Smith>
33 >>> Reporter.objects.get(id=2)
34 Traceback (most recent call last):
35 ...
36 DoesNotExist: Reporter matching query does not exist.
對Repoter的操作
對Article表的操作
1 # Import the models we created from our "news" app
2 >>> from news.models import Reporter, Article
3
4 # Create an article.
5 >>> from datetime import date
6 >>> a = Article(pub_date=date.today(), headline=‘Django is cool‘,
7 ... content=‘Yeah.‘, reporter=r)
8 >>> a.save()
9
10 # Now the article is in the database.
11 >>> Article.objects.all()
12 <QuerySet [<Article: Django is cool>]>
13
14 # Article objects get API access to related Reporter objects.
15 >>> r = a.reporter
16 >>> r.full_name
17 ‘John Smith‘
18
19 # And vice versa: Reporter objects get API access to Article objects.
20 >>> r.article_set.all()
21 <QuerySet [<Article: Django is cool>]>
22
23 # The API follows relationships as far as you need, performing efficient
24 # JOINs for you behind the scenes.
25 # This finds all articles by a reporter whose name starts with "John".
26 >>> Article.objects.filter(reporter__full_name__startswith=‘John‘)
27 <QuerySet [<Article: Django is cool>]>
28
29 # Change an object by altering its attributes and calling save().
30 >>> r.full_name = ‘Billy Goat‘
31 >>> r.save()
32
33 # Delete an object with delete().
34 >>> r.delete()
對Article的操作
4 動態管理接口
Django提供了功能完善的管理接口(administrative interface)
需要在admin.py中添加配置
mysite/news/admin.py
from django.contrib import admin
from . import models
admin.site.register(models.Article)
5 URLs的編寫(URL調度程序)
這個urls.py文件可以將URL的模式匹配與其相應的回調函數一一對應, 從而分離代碼
mysite/news/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r‘^articles/([0-9]{4})/$‘, views.year_archive),
url(r‘^articles/([0-9]{4})/([0-9]{2})/$‘, views.month_archive),
url(r‘^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$‘, views.article_detail),
]
這些是一些正則匹配來匹配輸入的URL
正則表達式中的括號可以獲取匹配成功的值
匹配的過程是從前往後依次匹配, 一旦匹配成功, 就會調用相應的view函數處理, 如果到最後都還時沒有匹配成功, 那麽就會返回特殊的視圖404
傳遞給view函數的有一個請求對象, 和上述中括號正則表達式捕獲到的值
/articles/2005/05/39323/
news.views.article_detail(request, ‘2005‘, ‘05‘, ‘39323‘)
6 編寫視圖(views)
編寫範例如下
mysite/news/views.py
from django.shortcuts import render
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)
最後返回的時候的html文件就用到了模板系統
7 編寫模板
在Django中可以設置一個目錄列表, 裏面有一個個存放模板的目錄(具體設置方法)
當查找模板的時候就依照順序在這些目錄中找
具體模板文件有
mysite/news/templates/news/year_archive.html
{% 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 %}
具體語法有
1) 值的獲取
{{ year }}
可以通過點的方式, 來進行屬性查找, 字典的鍵查找, 索引查找 和 函數調用
{{ article.headline }}
2) 模板過濾器(template filter)
變量後面用 | 來進行一下處理的方式, 類似於linux中的管道
格式化時間的方式如下
{{ article.pub_date|date:"F j, Y" }}
還可以自定義模板過濾器, 自定義模板標簽
3) 模板繼承
基本模板( base templates )如下
mysite/templates/base.html
{% load static %}
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<img src="{% static "images/sitelogo.png" %}" alt="Logo" />
{% block content %}{% endblock %}
</body>
</html>
繼承代碼為
{% extends "base.html" %}
02 - 看一眼Django都有啥