zoukankan      html  css  js  c++  java
  • ORM多表操作练习2(代码优化)

     

     

     

     orm_lx2_optimize.__init__.py

    import pymysql
    
    pymysql.install_as_MySQLdb()

    orm_lx2_optimize.settings.py

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'app01.apps.App01Config',  # app01应用注册
    ]
    
    
    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',
                ],
            },
        },
    ]
    
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': '20211204',
            'HOST': '127.0.0.1',
            'PORT': 3306,
            'USER': 'root',
            'PASSWORD': '123456'
        }
    }
    
    
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, "statics"),
    ]

    orm_lx2_optimize.urls.py

    from django.contrib import admin
    from django.urls import path, include
    from app01 import views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path("check/", views.check),
        path("delete/<int:number>/", views.delete),
        path("add/", views.add),
        path("edit/<int:number>/", views.edit),
    ]

    app01.models.py

    class Author(models.Model):
        id = models.AutoField(primary_key=True)
        name = models.CharField(max_length=32)
        age = models.IntegerField()
        gender = models.CharField(max_length=32)
        birthday = models.DateField()
    
    
    class Publish(models.Model):
        id = models.AutoField(primary_key=True)
        pub_name = models.CharField(max_length=32)
        pub_city = models.CharField(max_length=32)
        pub_email = models.EmailField()
    
    
    class Book(models.Model):
        id = models.AutoField(primary_key=True)
        title = models.CharField(max_length=32)
        price = models.DecimalField(max_digits=6, decimal_places=2)
        pub_date = models.DateField()
    
        publish = models.ForeignKey(to="Publish", to_field="id", on_delete=models.CASCADE)
    
        authors = models.ManyToManyField(to="Author")
    
    
    # 作者和出版社表,需自行手动添加几条数据

    app01.views.py

    from django.shortcuts import render, redirect
    from app01.models import *
    
    # Create your views here.
    
    
    def check(request):
        book_obj = Book.objects.filter().all()
        return render(request, "check.html", locals())
    
    
    def delete(request, number):
        Book.objects.filter(id=number).delete()
        return redirect("http://127.0.0.1:8000/check/")
    
    
    def add(request):
        if request.method == "GET":
            publish_list = Publish.objects.filter().all()
            author_list = Author.objects.filter().all()
            return render(request, "add.html", locals())
        # 先添加Book表的数据信息
        book_obj = Book.objects.create(
            title=request.POST.get("title"),
            price=request.POST.get("price"),
            pub_date=request.POST.get("pub_date"),
            publish_id=request.POST.get("publish"),
        )
        # 获取到选择作者的id的列表
        author_list = request.POST.getlist("author")
        # 多对多的关系绑定
        book_obj.authors.add(*author_list)
        return redirect("http://127.0.0.1:8000/check/")
    
    
    def edit(request, number):
        book_obj = Book.objects.filter(id=number).first()
        if request.method == 'GET':
            publish_list = Publish.objects.filter().all()
            author_list = Author.objects.filter().all()
            return render(request, "edit.html", locals())
        # 先修改Book表的数据信息
        Book.objects.filter(id=number).update(
            title=request.POST.get("title"),
            price=request.POST.get("price"),
            pub_date=request.POST.get("pub_date"),
            publish_id=request.POST.get("publish"),
        )
        # 获取到修改后作者的id的列表
        author_list = request.POST.getlist("author")
        # 多对多关系的重新设置
        book_obj.authors.set(author_list)
        return redirect("http://127.0.0.1:8000/check/")

    templates.check.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>查看书籍</title>
        <link rel="stylesheet" href="/static/bootstrap-3.4.1-dist/css/bootstrap.min.css">
        <script src="/static/bootstrap-3.4.1-dist/js/bootstrap.min.js"></script>
        <script src="/static/jQuery3.6.js"></script>
        <style>
            table {
                margin-top: 70px;
            }
        </style>
    </head>
    <body>
    <div class="container">
        <div class="row">
            <div class="col-md-10 col-md-offset-1">
                <h3>查看书籍</h3>
                <button class="btn btn-success pull-right"><a href="http://127.0.0.1:8000/add/">添加书籍</a></button>
                <table class="table table-bordered">
                    <thead>
                    <tr>
                        <th class="text-center">编号</th>
                        <th class="text-center">书籍名称</th>
                        <th class="text-center">书籍价格(元)</th>
                        <th class="text-center">出版日期</th>
                        <th class="text-center">出版社</th>
                        <th class="text-center">作者</th>
                        <th class="text-center">编辑操作</th>
                        <th class="text-center">删除操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    {# 传过来的是QuerySet对象,直接for循环取到每一个model对象,然后通过.的方式进行取值 #}
                    {% for book in book_obj %}
                        <tr class="text-center">
                        <td>{{ forloop.counter }}</td>
                        <td>{{ book.title }}</td>
                        <td>{{ book.price }}</td>
                        <td>{{ book.pub_date|date:'Y-m-d' }}</td>
                        <td>{{ book.publish.pub_name }}</td>
                        <td>
                            {# 通过连表的正向查询,查到当前书籍的所有作者,返回值是QuerySet对象 #}
                            {% for author in book.authors.all %}
                                {# 如果是最后一个值,那么后面不加',' #}
                                {% if forloop.last %}
                                    <span>{{ author.name }}</span>
                                {% else %}
                                    <span>{{ author.name }},</span>
                                {% endif %}
                            {% endfor %}
                        </td>
                        <td>
                            <button class="btn btn-sm btn-warning"><a href="http://127.0.0.1:8000/edit/{{ book.id }}/">编辑</a></button>
                        </td>
                        <td>
                            <button class="btn btn-sm btn-danger"><a href="http://127.0.0.1:8000/delete/{{ book.id }}/">删除</a></button>
                        </td>
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    </body>
    </html>

    templates.add.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>添加书籍</title>
        <link rel="stylesheet" href="/static/bootstrap-3.4.1-dist/css/bootstrap.min.css">
        <script src="/static/bootstrap-3.4.1-dist/js/bootstrap.min.js"></script>
        <script src="/static/jQuery3.6.js"></script>
    </head>
    <body>
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <h3>添加书籍</h3>
                <form action="" method="post">
                    {% csrf_token %}
                    <div class="form-group">
                        <label for="i1">书籍名称</label>
                        <input type="text" name="title" id="i1" class="form-control">
                    </div>
                    <div class="form-group">
                        <label for="i2">书籍价格</label>
                        <input type="text" name="price" id="i2" class="form-control">
                    </div>
                    <div class="form-group">
                        <label for="i3">出版日期</label>
                        <input type="date" name="pub_date" id="i3" class="form-control">
                    </div>
                    <div class="form-group">
                        <label for="i4">出版社</label>
                        <select name="publish" id="i4" class="form-control">
                            {# publish_list是一个QuerySet对象,通过for循环取到每一个model对象,然后通过.进行取值 #}
                            {% for publish in publish_list %}
                                <option value="{{ publish.id }}">{{ publish.pub_name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="i5">作者</label>
                        <select name="author" id="i5" class="form-control" multiple>
                            {# author_list是一个QuerySet对象,通过for循环取到每一个model对象,然后通过.进行取值 #}
                            {% for author in author_list %}
                                <option value="{{ author.id }}">{{ author.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <input type="submit" class="btn btn-success btn-block">
                </form>
            </div>
        </div>
    </div>
    </body>
    </html>

    templates.edit.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>编辑书籍</title>
        <link rel="stylesheet" href="/static/bootstrap-3.4.1-dist/css/bootstrap.min.css">
        <script src="/static/bootstrap-3.4.1-dist/js/bootstrap.min.js"></script>
        <script src="/static/jQuery3.6.js"></script>
    </head>
    <body>
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <h3>编辑书籍</h3>
                <form action="" method="post">
                    {% csrf_token %}
                    {# book_obj是一个model对象,可以直接用.进行取值 #}
                    <div class="form-group">
                        <label for="i1">书籍名称</label>
                        <input type="text" name="title" id="i1" class="form-control" value="{{ book_obj.title }}">
                    </div>
                    <div class="form-group">
                        <label for="i2">书籍价格</label>
                        <input type="text" name="price" id="i2" class="form-control" value="{{ book_obj.price }}">
                    </div>
                    <div class="form-group">
                        <label for="i3">出版日期</label>
                        <input type="date" name="pub_date" id="i3" class="form-control" value="{{ book_obj.pub_date|date:'Y-m-d' }}">
                    </div>
                    <div class="form-group">
                        <label for="i4">出版社</label>
                        <select name="publish" id="i4" class="form-control">
                            {% for publish in publish_list %}
                                {# 如果当前循环的publish对象和book_obj.publish的对象相等,那么就加上selected属性(默认选中) #}
                                {# book_obj.publish取出来的是一个对象,book_obj.publish_id取出来的是具体值 #}
                                {% if publish == book_obj.publish %}
                                    <option value="{{ publish.id }}" selected>{{ publish.pub_name }}</option>
                                {% else %}
                                    <option value="{{ publish.id }}">{{ publish.pub_name }}</option>
                                {% endif %}
                            {% endfor %}
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="i5">作者</label>
                        <select name="author" id="i5" class="form-control" multiple>
                            {% for author in author_list %}
                                {# book_obj.authors.all是连表的正向查询,查出当前书籍的所有作者的对象,结果是QuerySet #}
                                {# 如果循环的author对象在查询结果列表中,那么就加上selected属性 #}
                                {% if author in book_obj.authors.all %}
                                    <option value="{{ author.id }}" selected>{{ author.name }}</option>
                                {% else %}
                                    <option value="{{ author.id }}">{{ author.name }}</option>
                                {% endif %}
                            {% endfor %}
                        </select>
                    </div>
                    <input type="submit" class="btn btn-block btn-success">
                </form>
            </div>
        </div>
    </div>
    </body>
    </html>
    while True: print('studying...')
  • 相关阅读:
    SpringMVC拦截器
    SpringMVC异常
    SpringMVC文件上传
    SpringMVC返回值类型
    JVM字节码
    使用Apache JMeter进行测试
    Tomcat优化
    垃圾收集器
    GC常见算法
    VisualVM远程连接Tomcat
  • 原文地址:https://www.cnblogs.com/xuewei95/p/15643667.html
Copyright © 2011-2022 走看看