三种方式实现数据增删改查

Posted ligiao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了三种方式实现数据增删改查相关的知识,希望对你有一定的参考价值。

原生form实现   forms组件实现   modelform组件实现

技术图片

用原生form实现页面数据增删改查

前端代码

技术图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>书籍列表</title>
</head>
<body>
<a href="/book/add">
    <button>添加书籍</button>
</a>
<table border=1>
    <tr>
        <td>序号</td>
        <td>书籍名称</td>
        <td>书籍价格</td>
        <td>出版日期</td>
        <td>出版社</td>
        <td>作者</td>
        <td>操作</td>
    </tr>
    % for book in book_list %
        <tr>
            <td> forloop.counter </td>
            <td> book.title </td>
            <td> book.price </td>
            <td> book.publishDate|date:"Y-m-d" </td>
            <td> book.publish.name </td>
            <td> book.author.all </td>
            <td><a href="/book/edit book.pk ">
                <button>修改</button>
            </a>|<a href="/book/del?book_id= book.nid ">
                <button>删除</button>
            </a></td>
        </tr>
    % endfor %

</table>
</body>
</html>
查看
技术图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加书籍</title>
</head>
<body>
<form action="/book/add" method="post">
    % csrf_token %
    <p>书籍名称 <input name="book_name" type="text"></p>
    <p>书籍价格<input name="book_price" type="text"></p>
    <p>出版时间<input name="book_date" type="date"></p>

    <p>出版社 <select name="publish" id="">
        % for publish in publish_list %
            <option value=" publish.pk "> publish.name </option>
        % endfor %
    </select></p>

    <p>作者<select name="author" id="" multiple>
        % for author in author_list %
            <option value=" author.pk "> author.name </option>
        % endfor %

    </select>
    </p>

    <p><input type="submit" value="提交"></p>
</form>
</body>
</html>
添加
技术图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>编辑书籍</title>
</head>
<body>
<form action="" method="post">
    % csrf_token %
    <p>书籍名称 <input name="book_name" type="text" value=" book.title "></p>
    <p>书籍价格<input name="book_price" type="text" value=" book.price "></p>
    <p>出版时间<input name="book_date" type="date" value=" book.publishDate|date:"Y-d-m" "></p>

    <p>出版社 <select name="publish" id="">
        % for publish in publish_list %
            % if book.publish == publish %
                <option selected value=" publish.pk "> publish.name </option>
            % else %
                <option value=" publish.pk "> publish.name </option>
            % endif %

        % endfor %
    </select></p>

    <p>作者<select name="author" id="" multiple>
        % for author in author_list %
            % if author in book.author.all %
                <option selected value=" author.pk "> author.name </option>
            % else %
                <option value=" author.pk "> author.name </option>
            % endif %

        % endfor %

    </select>
    </p>

    <p><input type="submit" value="提交"></p>
</form>
</body>
</html>
修改

django views代码

技术图片
from django.shortcuts import render, redirect
from app01 import models


def book_list(request):  # 查看
    book_list = models.Book.objects.all()
    return render(request, "booklist.html", locals())


def book_add(request):  # 增加
    if request.method == "POST":
        book_name = request.POST.get("book_name")
        book_price = request.POST.get("book_price")
        book_date = request.POST.get("book_date")

        book_publish = request.POST.get("publish")

        book_author = request.POST.getlist("author")
        book_obj = models.Book.objects.create(title=book_name, price=book_price, publishDate=book_date,
                                              publish_id=book_publish)
        book_obj.author.add(*book_author)
        return redirect("/book_list")

    publish_list = models.Publish.objects.all()
    author_list = models.Author.objects.all()
    return render(request, "bookadd.html", locals())


def book_del(request):  # 删除
    book_id = request.GET.get("book_id")
    book_obj = models.Book.objects.filter(pk=book_id).first()
    book_obj.delete()
    return redirect("/book_list")


def book_edit(request, edit_book_id):  # 修改

    if request.method == "POST":
        book_name = request.POST.get("book_name")
        book_price = request.POST.get("book_price")
        book_date = request.POST.get("book_date")
        book_publish = request.POST.get("publish")
        book_author = request.POST.getlist("author")
        models.Book.objects.filter(pk=edit_book_id).update(title=book_name, price=book_price, publishDate=book_date,
                                                           publish_id=book_publish)
        models.Book.objects.filter(pk=edit_book_id).first().author.set(book_author)  # 不用打散列表,直接传
        return redirect("/book_list")

    book = models.Book.objects.filter(pk=edit_book_id).first()
    publish_list = models.Publish.objects.all()
    author_list = models.Author.objects.all()
    return render(request, "bookedit.html", locals())
增删改查

 

 用forms组件实现页面增删改查

前端代码

技术图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加书籍</title>
</head>
<body>
<form action="/book/add" method="post">
    % csrf_token %
    % for foo in form %
        <div> foo.label  foo </div>
    % endfor %
    <p><input type="submit" value="提交"></p>
</form>
</body>
</html>
添加

 django views代码

技术图片
class BookForm(forms.Form):  # 添加书籍的form类
    title = forms.CharField(max_length=32, label="书名")
    price = forms.DecimalField(max_digits=6, decimal_places=2, label="价格")
    date = forms.DateField(widget=widgets.TextInput(attrs="type": "date"), label="日期")
    # publish = forms.ChoiceField(choices=models.Publish.objects.all().values_list("pk","name"))  用ChoiceField写
    publish = forms.ModelChoiceField(queryset=models.Publish.objects.all(), label="出版社")  # 获取后台数据,在前台渲染成下拉菜单
    authors = forms.ModelMultipleChoiceField(queryset=models.Author.objects.all(), label="作者")


def book_add(request):  # 增加
    if request.method == "POST":
        form = BookForm(request.POST)  # 实例化一个校验对象,把接收到的数据传入
        if form.is_valid():  # 校验通过返回True,数据在对象.cleaned_data中
            book_name = form.cleaned_data.get("title")
            book_price = form.cleaned_data.get("price")
            book_date = form.cleaned_data.get("date")

            book_publish = form.cleaned_data.get("publish")  # 外键关系,接收的是一个对象

            book_author = form.cleaned_data.get("authors")  # 多对多,接收的是一个queryset
            book_obj = models.Book.objects.create(title=book_name, price=book_price, publishDate=book_date,
                                                  publish=book_publish)
            book_obj.author.add(*book_author)
            print(book_date, book_price, book_name, book_publish, book_author)
        return redirect("/book_list")
    form = BookForm()
    publish_list = models.Publish.objects.all()
    author_list = models.Author.objects.all()
    return render(request, "bookadd.html", locals())
form渲染前端

在这里forms组件只实现了增加数据的功能,其余只能借助原生form来完成

这里的作用是

  • 渲染页面的form表单
  • 对用户发送来的数据做校验

 

用ModelForm组件实现页面增删改查

 前端代码

技术图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加书籍</title>
</head>
<body>
<form action="/book/add" method="post">
    % csrf_token %
    % for foo in form %
        <div> foo.label  foo </div>
    % endfor %
    <p><input type="submit" value="提交"></p>
</form>
</body>
</html>
增加
技术图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>编辑书籍</title>
</head>
<body>
<form action="" method="post">
    % csrf_token %
    % for foo in form %
        <div> foo.label  foo </div>
    % endfor %
    <p><input type="submit" value="提交"></p>
</form>
</body>
</html>
编辑

 django views代码

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


def book_list(request):  # 查看
    book_list = models.Book.objects.all()
    return render(request, "booklist.html", locals())


class BookForm(ModelForm):
    class Meta:
        model = models.Book
        fields = ‘__all__‘  # 对数据库所有字段做转换
        labels = "title": "书籍名称", "price": "书籍价格", "publishDate": "出版日期", "publish": "出版社", "author": ‘作者‘


def book_add(request):  # 增加
    if request.method == "POST":
        form = BookForm(request.POST)  # 实例化一个校验对象,把接收到的数据传入
        if form.is_valid():  # 校验通过返回True,数据在对象.cleaned_data中
            form.save()  # form和model一对一关联,可以直接保存用户提交数据
            return redirect("/book_list")

    form = BookForm()
    return render(request, "bookadd.html", locals())


def book_del(request):  # 删除
    book_id = request.GET.get("book_id")
    book_obj = models.Book.objects.filter(pk=book_id).first()
    book_obj.delete()
    return redirect("/book_list")


def book_edit(request, edit_book_id):  # 修改
    book = models.Book.objects.filter(pk=edit_book_id).first()
    if request.method == "POST":
        form = BookForm(request.POST, instance=book)  # 传入要编辑的对象,直接修改
        if form.is_valid():
            form.save()
            return redirect("/book_list")

    form = BookForm(instance=book)  # 实例对象等于咱们要编辑的对象
    return render(request, "bookedit.html", locals())
View Code

相对于forms,ModelForm比之更强大,能够生成添加,修改数据的表单,为我们封装了很多存储修改验证对象的方法,使用起来更加方便

以上是关于三种方式实现数据增删改查的主要内容,如果未能解决你的问题,请参考以下文章

MySQL-增删改查简易操作

mysql数据库增删改查

Django ORM 数据库增删改查

django配置模型增删改查

库表的增删改查

mysql增删改查