溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

6、django操作表多對(duì)多實(shí)戰(zhàn)

發(fā)布時(shí)間:2020-08-13 07:06:13 來源:網(wǎng)絡(luò) 閱讀:372 作者:yht_1990 欄目:編程語言

圖書管理系統(tǒng)表設(shè)計(jì)結(jié)構(gòu)
6、django操作表多對(duì)多實(shí)戰(zhàn)

author的id對(duì)應(yīng)author_book的author_id
book的id對(duì)應(yīng)author_book的book_id

#########orm工具設(shè)置
D:\mysite\polls\models.py
orm:對(duì)像關(guān)系映射,將Python語法自動(dòng)轉(zhuǎn)換成sql語句

from django.db import models

#書
class Book(models.Model):
    id = models.AutoField(primary_key=True)  # 自增的ID主鍵
    #創(chuàng)建一個(gè)varchar(64)的唯一的不為空的字段
    title = models.CharField(max_length=64, null=False, unique=True)
    #和出版社關(guān)聯(lián)的外鍵字段
    publisher = models.ForeignKey(to="Publisher", on_delete=models.CASCADE)

#作者表
class Author(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=16, null=False, unique=True)
    #告訴ORM 我這張表和book表是多對(duì)多的關(guān)聯(lián)關(guān)系,ORM自動(dòng)幫我生成了第三張表
    book = models.ManyToManyField(to="Book")

    def __str__(self):
        return "<Author Object: {}>".format(self.name)

會(huì)生成三張表
6、django操作表多對(duì)多實(shí)戰(zhàn)
polls_book表
6、django操作表多對(duì)多實(shí)戰(zhàn)
polls_author表
6、django操作表多對(duì)多實(shí)戰(zhàn)
polls_author_books表
6、django操作表多對(duì)多實(shí)戰(zhàn)

#########主url設(shè)置

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('polls/',include('polls.urls')),
    path('admin/', admin.site.urls),
]

#########應(yīng)用url設(shè)置
D:\mysite\polls\urls.py

from django.urls import path

from . import views
app_name = 'polls'
urlpatterns = [

    #書相關(guān)的對(duì)應(yīng)關(guān)系
    path('book_list/', views.book_list,name='book_list'),
    path('add_book/', views.add_book,name='add_book'),  # 添加書籍
    path('delete_book/', views.delete_book,name='delete_book'),  # 刪除書籍
    path('edit_book/', views.edit_book,name='edit_book'),  # 編輯書籍

    # 作者相關(guān)的對(duì)應(yīng)關(guān)系
    path('author_list/', views.author_list,name='author_list'),  # 展示作者
    path('add_author/', views.add_author,name='add_author'),  # 添加作者
    path('delete_author/', views.delete_author,name='delete_author'),  # 刪除作者
    path('edit_author/', views.edit_author,name='edit_author'),  # 編輯作者

]

#########后端函數(shù)
D:\mysite\polls\views.py

from django.shortcuts import render,redirect,HttpResponse
from .models import Question,Publisher
from polls import models

#展示書的列表
def book_list(request):
    # 去數(shù)據(jù)庫中查詢所有的書籍
    all_book = models.Book.objects.all()
    #在HTML頁面完成字符串替換(渲染數(shù)據(jù))
    return render(request, "polls/book_list.html", {"all_book": all_book})

#添加書籍
def add_book(request):
    if request.method == "POST":
        new_title = request.POST.get("book_title")
        new_publisher_id = request.POST.get("publisher")
        #創(chuàng)建新書對(duì)象,自動(dòng)提交
        models.Book.objects.create(title=new_title, publisher_id=new_publisher_id)
        #返回到書籍列表頁
        return redirect("/polls/book_list/")

    #取到所有的出版社
    ret = models.Publisher.objects.all()
    return render(request, "polls/add_book.html", {"publisher_list": ret})

#刪除書籍
def delete_book(request):
    #從URL里面獲取要?jiǎng)h除的書籍的id值
    delete_id = request.GET.get("id")  # 從URL里面取數(shù)據(jù)
    #去刪除數(shù)據(jù)庫中刪除指定id的數(shù)據(jù)
    models.Book.objects.get(id=delete_id).delete()
    #返回書籍列表頁面, 查看是否刪除成功
    return redirect("/polls/book_list/")

#編輯書籍
def edit_book(request):
    if request.method == "POST":
        # 從提交的數(shù)據(jù)里面取,書名和書關(guān)聯(lián)的出版社
        edit_id = request.POST.get("id")
        new_title = request.POST.get("book_title")
        new_publisher_id = request.POST.get("publisher")
        #更新
        edit_book_obj = models.Book.objects.get(id=edit_id)
        edit_book_obj.title = new_title  # 更新書名
        edit_book_obj.publisher_id = new_publisher_id  # 更新書籍關(guān)聯(lián)的出版社
        #將修改提交到數(shù)據(jù)庫
        edit_book_obj.save()
        #返回書籍列表頁面,查看是否編輯成功
        return redirect("/polls/book_list/")

    #返回一個(gè)頁面,讓用戶編輯書籍信息
    #取到編輯的書的id值
    edit_id = request.GET.get("id")
    #根據(jù)id去數(shù)據(jù)庫中把具體的書籍對(duì)象拿到
    edit_book_obj = models.Book.objects.get(id=edit_id)
    ret = models.Publisher.objects.all()
    return render(
        request,
        "polls/edit_book.html",
        {"publisher_list": ret, "book_obj": edit_book_obj}
    )

#作者列表頁
def author_list(request):
    # 查詢所有的作者
    all_author = models.Author.objects.all()
    return render(request, "polls/author_list.html", {"author_list": all_author})

#添加作者
def add_author(request):
    if request.method == "POST":
        print("in post...")
        #取到提交的數(shù)據(jù)
        new_author_name = request.POST.get("author_name")
        #post提交的數(shù)據(jù)是多個(gè)值的時(shí)候一定會(huì)要用getlist,如多選的checkbox和多選的select
        books = request.POST.getlist("books")
        #創(chuàng)建作者
        new_author_obj = models.Author.objects.create(name=new_author_name)
        #把新作者和書籍建立對(duì)應(yīng)關(guān)系,自動(dòng)提交
        new_author_obj.book.set(books)
        #跳轉(zhuǎn)到作者列表頁面,查看是否添加成功!
        return redirect("/polls/author_list/")

    #查詢所有的書籍
    ret = models.Book.objects.all()
    return render(request, "polls/add_author.html", {"book_list": ret})

#刪除作者
def delete_author(request):
    # 從URL里面取到要?jiǎng)h除的作者id
    delete_id = request.GET.get("id")
    #根據(jù)ID值取到要?jiǎng)h除的作者對(duì)象,直接刪除
    #1. 去作者表把作者刪了
    #2. 去作者和書的關(guān)聯(lián)表,把對(duì)應(yīng)的關(guān)聯(lián)記錄刪除了
    models.Author.objects.get(id=delete_id).delete()
    #返回作者列表頁面
    return redirect("/polls/author_list/")

#編輯作者
def edit_author(request):

    # 如果編輯完提交數(shù)據(jù)過來
    if request.method == "POST":
        # 拿到提交過來的編輯后的數(shù)據(jù)
        edit_author_id = request.POST.get("author_id")
        new_author_name = request.POST.get("author_name")
        # 拿到編輯后作者關(guān)聯(lián)的書籍信息
        new_books = request.POST.getlist("books")
        # 根據(jù)ID找到當(dāng)前編輯的作者對(duì)象
        edit_author_obj = models.Author.objects.get(id=edit_author_id)
        # 更新作者的名字
        edit_author_obj.name = new_author_name
        # 更新作者關(guān)聯(lián)的書的對(duì)應(yīng)關(guān)系
        edit_author_obj.book.set(new_books)
        # 將修改提交到數(shù)據(jù)庫
        edit_author_obj.save()
        # 返回作者列表頁,查看是否編輯成功
        return redirect("/polls/author_list/")

    # 從URL里面取要編輯的作者的id信息
    edit_id = request.GET.get("id")
    # 找到要編輯的作者對(duì)象
    edit_author_obj = models.Author.objects.get(id=edit_id)

    # 查詢所有的書籍對(duì)象
    ret = models.Book.objects.all()
    return render(request, "polls/edit_author.html", {"book_list": ret, "author": edit_author_obj})

#########靜態(tài)html文件
#book列表頁
D:\mysite\polls\templates\polls\book_list.htmll

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

<h2>所有的書籍都在這里!</h2>
<a href="/polls/add_book/">添加書籍</a>

<table border="1">
    <thead>
        <tr>
            <th>id</th>
            <th>title</th>
            <th>publisher</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
        {% for i in all_book %}
            <tr>
            <td>{{ i.id }}</td>
            <td>{{ i.title }}</td>
            <td>{{ i.publisher.name }}</td>
            <td>
                <a href="/polls/delete_book/?id={{ i.id }}">刪除</a>
                <a href="/polls/edit_book/?id={{ i.id }}">編輯</a>
            </td>
            </tr>
        {% endfor %}
    </tbody>
</table>
</body>
</html>

##book添加頁

D:\mysite\polls\templates\polls\add_book.html

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

<h2>添加書籍</h2>
<form action="/polls/add_book/" method="post">
    <p>
        書名:<input type="text" name="book_title">
    </p>
    <p>
        出版社:
        <select name="publisher" >
            {% for publisher in publisher_list %}
                <option value="{{ publisher.id }}">{{ publisher.name }}</option>
            {% endfor %}
        </select>
    </p>
    <p>
         <input type="submit" value="提交">
    </p>

</form>

</body>
</html>

#book編輯頁

D:\mysite\polls\templates\polls\edit_book.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>編輯書籍</title>
</head>
<body>

<h2>編輯書籍</h2>

<form action="/polls/edit_book/" method="post">
    <input type="hidden"  name="id" value="{{ book_obj.id }}">
    <p>
        書名:
        <input type="text" name="book_title" value="{{ book_obj.title }}">
    </p>
    <p>
        出版社:
        <select name="publisher">

            {% for publisher in publisher_list %}

                {% if book_obj.publisher_id == publisher.id %}
                    {#  當(dāng)前書籍關(guān)聯(lián)的出版社才默認(rèn)選中#}
                    <option selected value="{{ publisher.id }}">{{ publisher.name }}</option>
                {% else %}
                    {# 其他的出版社不選中 #}
                    <option value="{{ publisher.id }}">{{ publisher.name }}</option>
                {% endif %}
            {% endfor %}

        </select>
    </p>
    <p>
        <input type="submit" value="提交">
    </p>
</form>

</body>
</html>

#作者列表頁
D:\mysite\polls\templates\polls\author_list.htm

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

<a href="/polls/add_author/">添加新的作者</a>

<h2>所有的作者</h2>

<table border="1">
    <thead>
    <tr>
        <th>#</th>
        <th>ID</th>
        <th>名字</th>
        <th>作品</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    {% for author in author_list %}
        <tr>
        <td>{{ forloop.counter }}</td>
        <td>{{ author.id }}</td>
        <td>{{ author.name }}</td>
        <td>
            {% for book in author.book.all %}
                {{ book.title }}?
        {% endfor %}
        </td>
        <td>
            <a href="/polls/delete_author/?id={{ author.id }}">刪除</a>
            <a href="/polls/edit_author/?id={{ author.id }}">編輯</a>
        </td>
        </tr>
    {% endfor %}
    </tbody>
</table>
</body>
</html>

#作者添加頁
D:\mysite\polls\templates\polls\add_author.html

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

<h2>添加作者</h2>

<form action="/polls/add_author/" method="post">
    <p>
       作者姓名:<input type="text" name="author_name">
    </p>

    <p>
        作品:
        <select multiple name="books">
            {% for book in book_list %}
            <option value="{{ book.id }}">{{ book.title }}</option>
            {% endfor %}
        </select>
    </p>

    <p>
        <input type="submit" value="提交">
    </p>

</form>

</body>
</html>

#作者編輯頁
D:\mysite\polls\templates\polls\edit_author.html

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

<h2>編輯作者</h2>

<form action="/polls/edit_author/" method="post">
    <input type="text" name="author_id" value="{{ author.id }}" >
    <p>
       作者姓名:<input type="text" name="author_name" value="{{ author.name }}">
    </p>

    <p>
        作品:
        <select multiple name="books">
            {% for book in book_list %}
{#                如果當(dāng)前這本書 在 當(dāng)前作者關(guān)聯(lián)的所有書 里面 #}
                {% if book in author.book.all %}
                    <option selected value="{{ book.id }}">{{ book.title }}</option>
                {% else %}
                <option  value="{{ book.id }}">{{ book.title }}</option>{% endif %}
            {% endfor %}
        </select>
    </p>

    <p>
        <input type="submit" value="提交">
    </p>

</form>

</body>
</html>

模板里author.book.all的含義
6、django操作表多對(duì)多實(shí)戰(zhàn)

#web展示
作者列表頁
6、django操作表多對(duì)多實(shí)戰(zhàn)

作者添加頁
6、django操作表多對(duì)多實(shí)戰(zhàn)

作者編輯頁
6、django操作表多對(duì)多實(shí)戰(zhàn)

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI