Python - Django - ORM 實例

準備工做:

首先建立一個名爲 Py_Django 的數據庫html

新建項目,名爲 mysite0python

建立完成後須要進行幾項配置mysql

mysite0/settings.py 下sql

首先是 html 文件相關數據庫

其次是數據庫配置django

最後註釋掉 CSRF 的代碼app

在 mysite0/__init__.py 中添加如下代碼函數

import pymysql

pymysql.install_as_MySQLdb()

app01/models.py 中寫上建立表的類oop

from django.db import models

# Create your models here.


# 出版社
class Publisher(models.Model):
    id = models.AutoField(primary_key=True)  # 自增的 id 主鍵
    # 建立一個 varchar(64) 的惟一的不爲空的字段
    name = models.CharField(max_length=64, null=False, unique=True)

執行一下兩條命令來建立表post

python manage.py makemigrations
python manage.py migrate

鏈接數據庫,建立三條數據

展現出版社列表:

publisher_list.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>出版社列表</title>
</head>
<body>

<table border="1">
    <thead>
    <tr>
        <th>序號</th>
        <th>ID</th>
        <th>出版社名稱</th>
    </tr>
    </thead>
    <tbody>
    {% for publisher in publisher_list %}
        <tr>
        <td>{{ forloop.counter }}</td>
        <td>{{ publisher.id }}</td>
        <td>{{ publisher.name }}</td>
        </tr>
    {% endfor %}

    </tbody>
</table>
</body>
</html>

第幾回循環,forloop.counter 的值就是多少

app01/views.py 中 publisher_list 函數:

from django.shortcuts import render
from app01 import models

# Create your views here.


# 展現出版社列表
def publisher_list(request):
    # 去數據庫查出全部的出版社,填充到 html 中,返回給用戶
    ret = models.Publisher.objects.all().order_by("id")  # order_by("id") 經過 id 進行排序
    return render(request, "publisher_list.html", {"publisher_list": ret})

在 mysite0/urls.py 中添加對應關係

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^publisher_list/', views.publisher_list),
]

運行結果:

 

添加出版社:

修改 publisher_list.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>出版社列表</title>
</head>
<body>

<table border="1">
    <thead>
    <tr>
        <th>序號</th>
        <th>ID</th>
        <th>出版社名稱</th>
    </tr>
    </thead>
    <tbody>
    {% for publisher in publisher_list %}
        <tr>
        <td>{{ forloop.counter }}</td>
        <td>{{ publisher.id }}</td>
        <td>{{ publisher.name }}</td>
        </tr>
    {% endfor %}

    </tbody>
</table>

<a href="/add_publisher/">添加新的出版社</a>

</body>
</html>

建立 add_publisher.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加出版社</title>
</head>
<body>

<h1>添加出版社</h1>

<form action="/add_publisher/" method="post">
    <input type="text" name="publisher_name">
    <input type="submit" value="提交">
</form>

</body>
</html>

在 app01/views.py 中添加 add_publisher 函數:

from django.shortcuts import render, redirect
from app01 import models

# Create your views here.


# 展現出版社列表
def publisher_list(request):
    # 去數據庫查出全部的出版社,填充到 html 中,返回給用戶
    ret = models.Publisher.objects.all().order_by("id")  # order_by("id") 經過 id 進行排序
    return render(request, "publisher_list.html", {"publisher_list": ret})


# 添加新的出版社
def add_publisher(request):
    # 若是是 POST 請求,就獲取用戶填寫的數據
    if request.method == "POST":
        new_publisher = request.POST.get("publisher_name")
        # 得到數據後去數據庫中新增一條數據
        models.Publisher.objects.create(name=new_publisher)
        # 添加成功後進行跳轉
        return redirect("/publisher_list/")

    # 用戶來到該界面返回的 html 頁面
    return render(request, "add_publisher.html")

 在 mysite0/urls.py 中添加對應關係

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^publisher_list/', views.publisher_list),
    url(r'^add_publisher/', views.add_publisher),
]

運行結果:

添加一個「丁出版社」

刪除出版社:

修改 publisher_list.html,添加刪除按鈕

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>出版社列表</title>
</head>
<body>

<table border="1">
    <thead>
    <tr>
        <th>序號</th>
        <th>ID</th>
        <th>出版社名稱</th>
        <th>操做</th>
    </tr>
    </thead>
    <tbody>
    {% for publisher in publisher_list %}
        <tr>
        <td>{{ forloop.counter }}</td>
        <td>{{ publisher.id }}</td>
        <td>{{ publisher.name }}</td>
        <td>
            <a href="/del_publisher/?id={{ publisher.id }}">刪除</a>
        </td>
        </tr>
    {% endfor %}

    </tbody>
</table>

<a href="/add_publisher/">添加新的出版社</a>

</body>
</html>

app01/views.py 中添加 del_publisher 函數

from django.shortcuts import render, redirect, HttpResponse
from app01 import models

# Create your views here.


# 展現出版社列表
def publisher_list(request):
    # 去數據庫查出全部的出版社,填充到 html 中,返回給用戶
    ret = models.Publisher.objects.all().order_by("id")  # order_by("id") 經過 id 進行排序
    return render(request, "publisher_list.html", {"publisher_list": ret})


# 添加新的出版社
def add_publisher(request):
    # 若是是 POST 請求,就獲取用戶填寫的數據
    if request.method == "POST":
        new_publisher = request.POST.get("publisher_name")
        # 得到數據後去數據庫中新增一條數據
        models.Publisher.objects.create(name=new_publisher)
        # 添加成功後進行跳轉
        return redirect("/publisher_list/")

    # 用戶來到該界面返回的 html 頁面
    return render(request, "add_publisher.html")


# 刪除出版社
def del_publisher(request):
    # 從 GET 請求的參數中拿到要刪除的 id 值
    del_id = request.GET.get('id', None)  # 取不到 id 值的話,默認爲 None
    # 若是取到 id 值,就去數據庫中刪除該 id 的數據
    if del_id:
        # 根據 id 查找數據,並刪除
        del_obj = models.Publisher.objects.get(id=del_id).delete()
        # 刪除後返回頁面
        return redirect("/publisher_list/")
    else:
        return HttpResponse("要刪除的數據不存在!")

mysite0/urls.py 中添加對應關係

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^publisher_list/', views.publisher_list),
    url(r'^add_publisher/', views.add_publisher),
    url(r'^del_publisher/', views.del_publisher),
]

運行結果:

點擊刪除丁出版社

頁面閃了一下,丁出版社就被刪除了

編輯出版社:

修改 publisher_list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>出版社列表</title>
</head>
<body>

<table border="1">
    <thead>
    <tr>
        <th>序號</th>
        <th>ID</th>
        <th>出版社名稱</th>
        <th>操做</th>
    </tr>
    </thead>
    <tbody>
    {% for publisher in publisher_list %}
        <tr>
        <td>{{ forloop.counter }}</td>
        <td>{{ publisher.id }}</td>
        <td>{{ publisher.name }}</td>
        <td>
            <a href="/del_publisher/?id={{ publisher.id }}">刪除</a>
            <a href="/edit_publisher/?id={{ publisher.id }}">編輯</a>
        </td>
        </tr>
    {% endfor %}

    </tbody>
</table>

<a href="/add_publisher/">添加新的出版社</a>

</body>
</html>

edit_publisher.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>編輯出版社</title>
</head>
<body>

<h1>編輯出版社</h1>

<form action="/edit_publisher/" method="post">
    <input type="text" name="id" value="{{ publisher.id }}" style="display: none">
    <input type="text" name="publisher_name" value="{{ publisher.name }}">
    <input type="submit" value="提交">
</form>

</body>
</html>

在 app01/views.py 中添加 edit_publisher 函數

from django.shortcuts import render, redirect, HttpResponse
from app01 import models

# Create your views here.


# 展現出版社列表
def publisher_list(request):
    # 去數據庫查出全部的出版社,填充到 html 中,返回給用戶
    ret = models.Publisher.objects.all().order_by("id")  # order_by("id") 經過 id 進行排序
    return render(request, "publisher_list.html", {"publisher_list": ret})


# 添加新的出版社
def add_publisher(request):
    # 若是是 POST 請求,就獲取用戶填寫的數據
    if request.method == "POST":
        new_publisher = request.POST.get("publisher_name")
        # 得到數據後去數據庫中新增一條數據
        models.Publisher.objects.create(name=new_publisher)
        # 添加成功後進行跳轉
        return redirect("/publisher_list/")

    # 用戶來到該界面返回的 html 頁面
    return render(request, "add_publisher.html")


# 刪除出版社
def del_publisher(request):
    # 從 GET 請求的參數中拿到要刪除的 id 值
    del_id = request.GET.get('id')
    # 若是取到 id 值,就去數據庫中刪除該 id 的數據
    if del_id:
        # 根據 id 查找數據,並刪除
        del_obj = models.Publisher.objects.get(id=del_id).delete()
        # 刪除後返回頁面
        return redirect("/publisher_list/")
    else:
        return HttpResponse("要刪除的數據不存在!")


# 編輯出版社
def edit_publisher(request):
    # 獲取 POST 發來的數據,並更新到數據庫中
    if request.method == "POST":
        # 獲取 POST 傳送來的 id 值和出版社
        edit_id = request.POST.get('id')
        new_name = request.POST.get('publisher_name')
        # 根據 id 取得出版社
        publisher = models.Publisher.objects.get(id=edit_id)
        publisher.name = new_name
        publisher.save()  # 把修改的結果提交到數據庫
        return redirect("/publisher_list/")  # 跳轉到列表頁面

    # 從 GET 請求中取得 id 值
    publisher_id = request.GET.get('id')
    if publisher_id:
        # 獲取當前編輯的出版社對象
        publisher_obj = models.Publisher.objects.get(id=publisher_id)
        return render(request, "edit_publisher.html", {"publisher": publisher_obj})
    else:
        return HttpResponse("編輯的出版社不存在!")

在 mysite0/urls.py 中添加對應關係

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^publisher_list/', views.publisher_list),
    url(r'^add_publisher/', views.add_publisher),
    url(r'^del_publisher/', views.del_publisher),
    url(r'^edit_publisher/', views.edit_publisher),
]

運行結果:

編輯「丙出版社」

改成「丁出版社」

相關文章
相關標籤/搜索