django基礎(chǔ)之?dāng)?shù)據(jù)庫(kù)操作方法(詳解)
Django 自稱(chēng)是“最適合開(kāi)發(fā)有限期的完美WEB框架”。本文參考《Django web開(kāi)發(fā)指南》,快速搭建一個(gè)blog 出來(lái),在中間涉及諸多知識(shí)點(diǎn),這里不會(huì)詳細(xì)說(shuō)明,如果你是第一次接觸Django ,本文會(huì)讓你在感性上對(duì)Django有個(gè)認(rèn)識(shí),完成本文操作后會(huì)讓你有興趣閱讀的相關(guān)書(shū)籍和文檔。
本文客操作的環(huán)境,如無(wú)特別說(shuō)明,后續(xù)都以下面的環(huán)境為基礎(chǔ):
===================
Windows 7/10
python 3.5
Django 1.10
===================
1:創(chuàng)建工程
創(chuàng)建mysite工程項(xiàng)目:
E:/WWWROOT/python/> django-admin.py startproject mysite
當(dāng)然,前提是你已經(jīng)設(shè)置好了python的環(huán)境變量!
如果是IDE工具(本文使用的是PyCharm4.0),在File -> New Project -> Django中創(chuàng)建工程
創(chuàng)建完成后,工程目錄結(jié)構(gòu)如下:

manage.py ----- Django項(xiàng)目里面的工具,通過(guò)它可以調(diào)用django shell和數(shù)據(jù)庫(kù)等。
settings.py ---- 包含了項(xiàng)目的默認(rèn)設(shè)置,包括數(shù)據(jù)庫(kù)信息,調(diào)試標(biāo)志以及其他一些工作的變量。
urls.py ----- 負(fù)責(zé)把URL模式映射到應(yīng)用程序。
2:創(chuàng)建blog應(yīng)用
在python里叫做app
E:\WWWROOT\python\mysite>python manage.py startapp blog
完成后,會(huì)在項(xiàng)目中生成一個(gè)blog的文件夾

3:數(shù)據(jù)庫(kù)操作
初始化數(shù)據(jù)庫(kù):
python 自帶SQLite數(shù)據(jù)庫(kù),Django支持各種主流的數(shù)據(jù)庫(kù),這里我們首先使用SQLite,如果使用其它數(shù)據(jù)庫(kù)請(qǐng)?jiān)趕ettings.py文件中設(shè)置。數(shù)據(jù)庫(kù)默認(rèn)的配置為:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
使用默認(rèn)的數(shù)據(jù)配置來(lái)初始化數(shù)據(jù)庫(kù):
E:\WWWROOT\python\mysite>python manage.py migrate
命令執(zhí)行完成后,會(huì)生成一些數(shù)據(jù)表:

Django自帶有一個(gè)WEB 后臺(tái),下面創(chuàng)建WEB后臺(tái)的用戶(hù)名與密碼:
E:\WWWROOT\python\mysite>python manage.py createsuperuser System check identified some issues: WARNINGS: ?: (1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your default TEMPLATES dict: TEMPLATE_DIRS. Username (leave blank to use 'administrator'): root Email address: admin@admin.com Password: Password (again): Superuser created successfully.
接下來(lái)我們使用上面創(chuàng)建的賬號(hào)密碼登錄后臺(tái)試試。要登錄后臺(tái),必須在settings.py文件中將上面創(chuàng)建的APP也就是blog添加進(jìn)來(lái):
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ]
注意后面必須要有個(gè)逗號(hào)!
啟動(dòng)django容器:
E:\WWWROOT\python\mysite>python manage.py runserver
默認(rèn)使用的WEB地址為http://127.0.0.1,端口為8000,使用該地址與端口訪(fǎng)問(wèn)首頁(yè):

下面訪(fǎng)問(wèn)django的后臺(tái):http://127.0.0.1/admin

使用上面創(chuàng)建的用戶(hù)與密碼即可登錄到后臺(tái)!
如果你想連接mysql數(shù)據(jù)庫(kù)而不使用SQLite,那么首先你必須得安裝pymysql模塊,python3.5版本不再支持MySQLdb模塊!安裝完成后請(qǐng)看下面的操作:
首先在settings.py文件配置數(shù)據(jù)庫(kù):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '127.0.0.1',
'PORT': 3306,
'NAME': 'djangodb',
'USER': 'root',
'PASSWORD': 'root',
}
}
在mysql數(shù)據(jù)中創(chuàng)建一個(gè)djangodb的數(shù)據(jù)庫(kù),然后在mysite/__init__.py文件中加入以下代碼:
import pymysql pymysql.install_as_MySQLdb()
命令行運(yùn)行:
E:\WWWROOT\python\mysite>python manage.py makemigrations E:\WWWROOT\python\mysite>python manage.py migrate
這樣在mysql數(shù)據(jù)庫(kù)他初始化數(shù)據(jù)表:

這里為了演示,我將數(shù)據(jù)庫(kù)的鏈接改為SQLite
創(chuàng)建一張UseInfo表,并創(chuàng)建字段:
現(xiàn)在我們打開(kāi)blog目錄下的models.py文件,這是我們定義blog數(shù)據(jù)結(jié)構(gòu)的地方。打開(kāi)mysite/blog/models.py 文件進(jìn)行修改:
from django.db import models # Create your models here. class UserInfo(models.Model): username = models.CharField(max_length=32) password = models.CharField(max_length=32) age = models.IntegerField()
命令行執(zhí)行:
E:\WWWROOT\python\mysite>python manage.py makemigrations E:\WWWROOT\python\mysite>python manage.py migrate
完成后會(huì)在數(shù)據(jù)庫(kù)創(chuàng)建一張數(shù)據(jù)表:

從上圖中可以看出,Django默認(rèn)會(huì)以APP名為數(shù)據(jù)表前綴,以類(lèi)名為數(shù)據(jù)表名!
創(chuàng)建的字段如下圖:

從上圖可以看出,Django會(huì)默認(rèn)加上一個(gè)id字段,該字段為主鍵且自增長(zhǎng)
在blog_UserInfo表中添加數(shù)據(jù):
Django是在views.py文件中,通過(guò)導(dǎo)入models.py文件來(lái)創(chuàng)建數(shù)據(jù)的:
from django.shortcuts import render
# Create your views here.
from blog import models #導(dǎo)入blog模塊
from django.shortcuts import HttpResponse
def db_handle(request):
models.UserInfo.objects.create(username='andy',password='123456',age=33)
return HttpResponse('OK')
下面我們配置路由,以便讓瀏覽器能夠訪(fǎng)問(wèn)到views.py文件:
from django.conf.urls import url from django.contrib import admin from blog import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^db_handle', views.db_handle), ]
下面我們來(lái)訪(fǎng)問(wèn)http://127.0.0.1/db_handle

查看數(shù)據(jù)庫(kù)是否創(chuàng)建成功:

上面就是創(chuàng)建表數(shù)據(jù),也可以通過(guò)字典的格式來(lái)創(chuàng)建表數(shù)據(jù):
def db_handle(request):
# models.UserInfo.objects.create(username='andy',password='123456',age=33)
dic = {"username":"bruce","password":"123456","age":23}
models.UserInfo.objects.create(**dic)
return HttpResponse('OK')
通過(guò)上面的方法,我們多創(chuàng)建幾條數(shù)據(jù),完成后如下圖所示:

刪除表數(shù)據(jù):
views.py文件如下:
from django.shortcuts import render
# Create your views here.
from blog import models
from django.shortcuts import HttpResponse
def db_handle(request):
# models.UserInfo.objects.create(username='andy',password='123456',age=33)
# dic = {"username":"bruce","password":"123456","age":23}
# models.UserInfo.objects.create(**dic)
models.UserInfo.objects.filter(id=2).delete()
return HttpResponse('OK')
操作方法同上,在瀏覽器中執(zhí)行一遍,數(shù)據(jù)中的id=2的數(shù)據(jù)即被刪除:

修改表數(shù)據(jù):
from django.shortcuts import render
# Create your views here.
from blog import models
from django.shortcuts import HttpResponse
def db_handle(request):
models.UserInfo.objects.filter(id=1).update(age=18) #找到id=1的數(shù)據(jù),將age改為18
return HttpResponse('OK')
數(shù)據(jù)的查詢(xún):
為了讓查詢(xún)出來(lái)的數(shù)據(jù)更加直觀(guān)地顯示出來(lái),這里我們將使用Django的模板功能,讓查詢(xún)出來(lái)的數(shù)據(jù)在WEB瀏覽器中展示出來(lái)
在templates目錄下新建一個(gè)t1.html的文件,內(nèi)容如下:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Django操作數(shù)據(jù)庫(kù)</title>
</head>
<body>
<table border="1">
<tr>
<th>用戶(hù)名</th>
<th>密碼</th>
<th>年齡</th>
</tr>
{% for item in li %}
<tr>
<td>{{ item.username }}</td>
<td>{{ item.password }}</td>
<td>{{ item.age }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
views.py文件查詢(xún)數(shù)據(jù),并指定調(diào)用的模板文件,內(nèi)容如下:
from django.shortcuts import render
# Create your views here.
from blog import models
from django.shortcuts import HttpResponse
def db_handle(request):
user_list_obj = models.UserInfo.objects.all()
return render(request,'t1.html',{'li':user_list_obj})
注意:由于這里是在工程下面的templates目錄下建立的模板,而不是在blog應(yīng)用中創(chuàng)建的模板,上面views.py文件中調(diào)用的t1.html模板,運(yùn)行時(shí)會(huì)出現(xiàn)找不到t1.html模板的錯(cuò)誤,為了能找到mysite/templates下的模板文件,我們還需要在settings.py文件配置模板的路徑:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')], #配置模板路徑
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
下面就可以在瀏覽器中查看:

引入JS,CSS等靜態(tài)文件:
在mysite目錄下新建一個(gè)static目錄,將JS,CSS文件都放在此目錄下!并在settings.py文件中指定static目錄:
STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), )
表單提交數(shù)據(jù):
在Django中要使用post方式提交表單,需要在settings.py配置文件中將下面一行的內(nèi)容給注釋掉:
# 'django.middleware.csrf.CsrfViewMiddleware',
提交表單(這里仍然使用了t1.html):
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Django表單</title>
<link type="text/css" href="/static/base.css" rel="external nofollow" rel="stylesheet" />
</head>
<body>
<table border="1">
<tr>
<th>用戶(hù)名</th>
<th>密碼</th>
<th>年齡</th>
</tr>
{% for item in li %}
<tr>
<td>{{ item.username }}</td>
<td>{{ item.password }}</td>
<td>{{ item.age }}</td>
</tr>
{% endfor %}
</table>
<form action="/db_handle/" method="post">
<p><input name="username" /></p>
<p><input name="password" /></p>
<p><input name="age" /></p>
<p><input type="submit" value="submit" /></p>
</form>
</body>
</html>
寫(xiě)入數(shù)據(jù)庫(kù)(views.py):
from django.shortcuts import render
# Create your views here.
from blog import models
from django.shortcuts import HttpResponse
def db_handle(request):
if request.method == "POST":
models.UserInfo.objects.create(username=request.POST['username'],password=request.POST['password'],age=request.POST['age'])
user_list_obj = models.UserInfo.objects.all()
return render(request, 't1.html', {'li': user_list_obj})
提交數(shù)據(jù)后,如下圖:

Django執(zhí)行流程

以上這篇django基礎(chǔ)之?dāng)?shù)據(jù)庫(kù)操作方法(詳解)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python利用imshow制作自定義漸變填充柱狀圖(colorbar)
這篇文章主要介紹了Python利用imshow制作自定義漸變填充柱狀圖(colorbar),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
Python實(shí)現(xiàn)多線(xiàn)程并發(fā)請(qǐng)求測(cè)試的腳本
這篇文章主要為大家分享了一個(gè)Python實(shí)現(xiàn)多線(xiàn)程并發(fā)請(qǐng)求測(cè)試的腳本,文中的示例代碼簡(jiǎn)潔易懂,具有一定的借鑒價(jià)值,需要的小伙伴可以了解一下2023-06-06
Python圖像運(yùn)算之頂帽運(yùn)算和底帽運(yùn)算詳解
數(shù)學(xué)形態(tài)學(xué)是應(yīng)用于圖像處理和模式識(shí)別領(lǐng)域的新方法。數(shù)學(xué)形態(tài)學(xué)表示以形態(tài)為基礎(chǔ)對(duì)圖像進(jìn)行分析的數(shù)學(xué)工具,基本思想是用具有一定形態(tài)的結(jié)構(gòu)元素去量度和提取圖像中對(duì)應(yīng)形狀以達(dá)到對(duì)圖像分析和識(shí)別的目的。本文將為大家介紹頂帽運(yùn)算和底帽運(yùn)算,需要的可以參考一下2022-07-07
Python使用BeautifulSoup庫(kù)解析網(wǎng)頁(yè)
在Python的網(wǎng)絡(luò)爬蟲(chóng)中,網(wǎng)頁(yè)解析是一項(xiàng)重要的技術(shù)。而在眾多的網(wǎng)頁(yè)解析庫(kù)中,BeautifulSoup庫(kù)憑借其簡(jiǎn)單易用而廣受歡迎,在本篇文章中,我們將學(xué)習(xí)BeautifulSoup庫(kù)的基本用法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2023-08-08

