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

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

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

Django自帶有一個WEB 后臺,下面創(chuàng)建WEB后臺的用戶名與密碼:
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.
接下來我們使用上面創(chuàng)建的賬號密碼登錄后臺試試。要登錄后臺,必須在settings.py文件中將上面創(chuàng)建的APP也就是blog添加進來:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ]
注意后面必須要有個逗號!
啟動django容器:
E:\WWWROOT\python\mysite>python manage.py runserver
默認使用的WEB地址為http://127.0.0.1,端口為8000,使用該地址與端口訪問首頁:

下面訪問django的后臺:http://127.0.0.1/admin

使用上面創(chuàng)建的用戶與密碼即可登錄到后臺!
如果你想連接mysql數(shù)據(jù)庫而不使用SQLite,那么首先你必須得安裝pymysql模塊,python3.5版本不再支持MySQLdb模塊!安裝完成后請看下面的操作:
首先在settings.py文件配置數(shù)據(jù)庫:
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)建一個djangodb的數(shù)據(jù)庫,然后在mysite/__init__.py文件中加入以下代碼:
import pymysql pymysql.install_as_MySQLdb()
命令行運行:
E:\WWWROOT\python\mysite>python manage.py makemigrations E:\WWWROOT\python\mysite>python manage.py migrate
這樣在mysql數(shù)據(jù)庫他初始化數(shù)據(jù)表:

這里為了演示,我將數(shù)據(jù)庫的鏈接改為SQLite
創(chuàng)建一張UseInfo表,并創(chuàng)建字段:
現(xiàn)在我們打開blog目錄下的models.py文件,這是我們定義blog數(shù)據(jù)結(jié)構(gòu)的地方。打開mysite/blog/models.py 文件進行修改:
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
完成后會在數(shù)據(jù)庫創(chuàng)建一張數(shù)據(jù)表:

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

從上圖可以看出,Django會默認加上一個id字段,該字段為主鍵且自增長
在blog_UserInfo表中添加數(shù)據(jù):
Django是在views.py文件中,通過導入models.py文件來創(chuàng)建數(shù)據(jù)的:
from django.shortcuts import render
# Create your views here.
from blog import models #導入blog模塊
from django.shortcuts import HttpResponse
def db_handle(request):
models.UserInfo.objects.create(username='andy',password='123456',age=33)
return HttpResponse('OK')
下面我們配置路由,以便讓瀏覽器能夠訪問到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), ]
下面我們來訪問http://127.0.0.1/db_handle

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

上面就是創(chuàng)建表數(shù)據(jù),也可以通過字典的格式來創(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')
通過上面的方法,我們多創(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ù)的查詢:
為了讓查詢出來的數(shù)據(jù)更加直觀地顯示出來,這里我們將使用Django的模板功能,讓查詢出來的數(shù)據(jù)在WEB瀏覽器中展示出來
在templates目錄下新建一個t1.html的文件,內(nèi)容如下:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Django操作數(shù)據(jù)庫</title>
</head>
<body>
<table border="1">
<tr>
<th>用戶名</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文件查詢數(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應用中創(chuàng)建的模板,上面views.py文件中調(diào)用的t1.html模板,運行時會出現(xiàn)找不到t1.html模板的錯誤,為了能找到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目錄下新建一個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>用戶名</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>
寫入數(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):
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ǔ)之數(shù)據(jù)庫操作方法(詳解)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用Python腳本在Linux下實現(xiàn)部分Bash Shell的教程
這篇文章主要介紹了使用Python腳本在Linux下實現(xiàn)部分Bash Shell的教程,包括一些簡單的輸入輸出和郵件功能,需要的朋友可以參考下2015-04-04
Selenium 模擬瀏覽器動態(tài)加載頁面的實現(xiàn)方法
這篇文章主要介紹了Selenium 模擬瀏覽器動態(tài)加載頁面的實現(xiàn)方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05

