温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

6、django操作表多对多实战

发布时间:2020-08-13 07:06:13 来源:网络 阅读:352 作者:yht_1990 栏目:编程语言

图书管理系统表设计结构
6、django操作表多对多实战

author的id对应author_book的author_id
book的id对应author_book的book_id

#########orm工具设置
D:\mysite\polls\models.py
orm:对像关系映射,将Python语法自动转换成sql语句

from django.db import models

#书
class Book(models.Model):
    id = models.AutoField(primary_key=True)  # 自增的ID主键
    #创建一个varchar(64)的唯一的不为空的字段
    title = models.CharField(max_length=64, null=False, unique=True)
    #和出版社关联的外键字段
    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表是多对多的关联关系,ORM自动帮我生成了第三张表
    book = models.ManyToManyField(to="Book")

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

会生成三张表
6、django操作表多对多实战
polls_book表
6、django操作表多对多实战
polls_author表
6、django操作表多对多实战
polls_author_books表
6、django操作表多对多实战

#########主url设置

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

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

#########应用url设置
D:\mysite\polls\urls.py

from django.urls import path

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

    #书相关的对应关系
    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'),  # 编辑书籍

    # 作者相关的对应关系
    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'),  # 编辑作者

]

#########后端函数
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):
    # 去数据库中查询所有的书籍
    all_book = models.Book.objects.all()
    #在HTML页面完成字符串替换(渲染数据)
    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")
        #创建新书对象,自动提交
        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里面获取要删除的书籍的id值
    delete_id = request.GET.get("id")  # 从URL里面取数据
    #去删除数据库中删除指定id的数据
    models.Book.objects.get(id=delete_id).delete()
    #返回书籍列表页面, 查看是否删除成功
    return redirect("/polls/book_list/")

#编辑书籍
def edit_book(request):
    if request.method == "POST":
        # 从提交的数据里面取,书名和书关联的出版社
        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  # 更新书籍关联的出版社
        #将修改提交到数据库
        edit_book_obj.save()
        #返回书籍列表页面,查看是否编辑成功
        return redirect("/polls/book_list/")

    #返回一个页面,让用户编辑书籍信息
    #取到编辑的书的id值
    edit_id = request.GET.get("id")
    #根据id去数据库中把具体的书籍对象拿到
    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...")
        #取到提交的数据
        new_author_name = request.POST.get("author_name")
        #post提交的数据是多个值的时候一定会要用getlist,如多选的checkbox和多选的select
        books = request.POST.getlist("books")
        #创建作者
        new_author_obj = models.Author.objects.create(name=new_author_name)
        #把新作者和书籍建立对应关系,自动提交
        new_author_obj.book.set(books)
        #跳转到作者列表页面,查看是否添加成功!
        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里面取到要删除的作者id
    delete_id = request.GET.get("id")
    #根据ID值取到要删除的作者对象,直接删除
    #1. 去作者表把作者删了
    #2. 去作者和书的关联表,把对应的关联记录删除了
    models.Author.objects.get(id=delete_id).delete()
    #返回作者列表页面
    return redirect("/polls/author_list/")

#编辑作者
def edit_author(request):

    # 如果编辑完提交数据过来
    if request.method == "POST":
        # 拿到提交过来的编辑后的数据
        edit_author_id = request.POST.get("author_id")
        new_author_name = request.POST.get("author_name")
        # 拿到编辑后作者关联的书籍信息
        new_books = request.POST.getlist("books")
        # 根据ID找到当前编辑的作者对象
        edit_author_obj = models.Author.objects.get(id=edit_author_id)
        # 更新作者的名字
        edit_author_obj.name = new_author_name
        # 更新作者关联的书的对应关系
        edit_author_obj.book.set(new_books)
        # 将修改提交到数据库
        edit_author_obj.save()
        # 返回作者列表页,查看是否编辑成功
        return redirect("/polls/author_list/")

    # 从URL里面取要编辑的作者的id信息
    edit_id = request.GET.get("id")
    # 找到要编辑的作者对象
    edit_author_obj = models.Author.objects.get(id=edit_id)

    # 查询所有的书籍对象
    ret = models.Book.objects.all()
    return render(request, "polls/edit_author.html", {"book_list": ret, "author": edit_author_obj})

#########静态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 %}
                    {#  当前书籍关联的出版社才默认选中#}
                    <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 %}
{#                如果当前这本书 在 当前作者关联的所有书 里面 #}
                {% 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操作表多对多实战

#web展示
作者列表页
6、django操作表多对多实战

作者添加页
6、django操作表多对多实战

作者编辑页
6、django操作表多对多实战

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI