09 django模型层_单表练习

Deadly 提交于 2020-05-01 19:33:20

模型层(单表练习)

图书管理系统:

实现功能:book单表的增删改查

查询操作练习:

1 查询人民出版社出版过的价格大于200的书籍

2 查询20178月出版的所有以py开头的书籍名称

3 查询价格为50,100或者150的所有书籍名称及其出版社名

4 查询价格在100200之间的所有书籍名称及其价格

5 查询所有人民出版社出版的书籍的价格(从高到低排序,去重)

 

效果:

 

目录结构:

 

06 django模型层\book\book\settings.py

  1 """
  2 Django settings for book project.
  3 
  4 Generated by 'django-admin startproject' using Django 2.2.3.
  5 
  6 For more information on this file, see
  7 https://docs.djangoproject.com/en/2.2/topics/settings/
  8 
  9 For the full list of settings and their values, see
 10 https://docs.djangoproject.com/en/2.2/ref/settings/
 11 """
 12 
 13 import os
 14 
 15 # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
 16 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 17 
 18 
 19 # Quick-start development settings - unsuitable for production
 20 # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
 21 
 22 # SECURITY WARNING: keep the secret key used in production secret!
 23 SECRET_KEY = 'cex-c#ja^@=p_dp#ak0-@=^ws!_-f6g#*52jb5!3%xhe4!dc^*'
 24 
 25 # SECURITY WARNING: don't run with debug turned on in production!
 26 DEBUG = True
 27 
 28 ALLOWED_HOSTS = []
 29 
 30 
 31 # Application definition
 32 
 33 INSTALLED_APPS = [
 34     'django.contrib.admin',
 35     'django.contrib.auth',
 36     'django.contrib.contenttypes',
 37     'django.contrib.sessions',
 38     'django.contrib.messages',
 39     'django.contrib.staticfiles',
 40     # 'book_app01.apps.BookApp01Config',
 41     'book_app01',
 42 ]
 43 
 44 MIDDLEWARE = [
 45     'django.middleware.security.SecurityMiddleware',
 46     'django.contrib.sessions.middleware.SessionMiddleware',
 47     'django.middleware.common.CommonMiddleware',
 48     'django.middleware.csrf.CsrfViewMiddleware',
 49     'django.contrib.auth.middleware.AuthenticationMiddleware',
 50     'django.contrib.messages.middleware.MessageMiddleware',
 51     'django.middleware.clickjacking.XFrameOptionsMiddleware',
 52 ]
 53 
 54 ROOT_URLCONF = 'book.urls'
 55 
 56 TEMPLATES = [
 57     {
 58         'BACKEND': 'django.template.backends.django.DjangoTemplates',
 59         'DIRS': [os.path.join(BASE_DIR,  'templates')],
 60         'APP_DIRS': True,
 61         'OPTIONS': {
 62             'context_processors': [
 63                 'django.template.context_processors.debug',
 64                 'django.template.context_processors.request',
 65                 'django.contrib.auth.context_processors.auth',
 66                 'django.contrib.messages.context_processors.messages',
 67             ],
 68         },
 69     },
 70 ]
 71 
 72 WSGI_APPLICATION = 'book.wsgi.application'
 73 
 74 
 75 # Database
 76 # https://docs.djangoproject.com/en/2.2/ref/settings/#databases
 77 
 78 # DATABASES = {
 79 #     'default': {
 80 #         'ENGINE': 'django.db.backends.sqlite3',
 81 #         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
 82 #     }
 83 # }
 84 
 85 
 86 # Password validation
 87 # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
 88 
 89 AUTH_PASSWORD_VALIDATORS = [
 90     {
 91         'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
 92     },
 93     {
 94         'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
 95     },
 96     {
 97         'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
 98     },
 99     {
100         'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
101     },
102 ]
103 
104 
105 # Internationalization
106 # https://docs.djangoproject.com/en/2.2/topics/i18n/
107 
108 LANGUAGE_CODE = 'en-us'
109 
110 TIME_ZONE = 'UTC'
111 
112 USE_I18N = True
113 
114 USE_L10N = True
115 
116 USE_TZ = True
117 
118 
119 # Static files (CSS, JavaScript, Images)
120 # https://docs.djangoproject.com/en/2.2/howto/static-files/
121 
122 STATIC_URL = '/static/'
123 
124 STATICFILES_DIRS = [
125     os.path.join(BASE_DIR, 'statics')
126 ]
127 DATABASES = {
128     'default': {
129         'ENGINE': 'django.db.backends.mysql',
130         'NAME':'orm',# 要连接的数据库,连接前需要创建好
131         'USER':'root',# 连接数据库的用户名
132         'PASSWORD':'root',# 连接数据库的密码
133         'HOST':'127.0.0.1',# 连接主机,默认本级
134         'PORT':3306 #  端口 默认3306
135     }
136 }
137 
138 LOGGING = {
139     'version': 1,
140     'disable_existing_loggers': False,
141     'handlers': {
142         'console':{
143             'level':'DEBUG',
144             'class':'logging.StreamHandler',
145         },
146     },
147     'loggers': {
148         'django.db.backends': {
149             'handlers': ['console'],
150             'propagate': True,
151             'level':'DEBUG',
152         },
153     }
154 }
View Code

 

06 django模型层\book\book\__init__.py

import pymysql
pymysql.install_as_MySQLdb()

 

06 django模型层\book\book\urls.py

from django.contrib import admin
from django.urls import path,re_path,include
urlpatterns = [
    path('admin/', admin.site.urls),
    re_path('^app01/', include(('book_app01.urls','book_app01'))),
]

 

06 django模型层\book\book_app01\models.py

from django.db import models

# Create your models here.

class Book(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=32,unique=True)
    state = models.BooleanField()
    pub_date = models.DateField()
    price=models.DecimalField(max_digits=8,decimal_places=2)
    publish=models.CharField(max_length=32)

    def __str__(self):
        return self.title

 

06 django模型层\book\book_app01\urls.py

from django.urls import path,re_path,include
from book_app01 import views

urlpatterns = [
    path('book/', views.book),
    path('book/add', views.add_book),
    re_path(r'book/(\d+)/update', views.update_book),
    re_path(r'book/(\d+)/delete', views.delete_book),
]

 

06 django模型层\book\book_app01\views.py

 1 from django.shortcuts import render,redirect
 2 from book_app01.models import Book
 3 
 4 # Create your views here.
 5 
 6 
 7 def book(request):
 8     method = request.method
 9     req = request.POST if request.POST else request.GET
10     try:
11         title = req.get('title') if req.get('title') else ''
12     except:
13         title = ''
14     book_list = Book.objects.filter(title__contains=title)
15     '''
16         # 1 查询人民出版社出版过的价格大于200的书籍
17         res = Book.objects.filter(publish="人民出版社",price__gt=200)
18         # 2 查询2017年8月出版的所有以py开头的书籍名称
19         res = Book.objects.filter(pub_date__contains="2017-08",title__startswith='py').values('title')
20         # 3 查询价格为50,100或者150的所有书籍名称及其出版社名
21         res = Book.objects.filter(price__in=[50,100,150]).values('title','publish')
22         # 4 查询价格在100到200之间的所有书籍名称及其价格
23         res = Book.objects.filter(price__range=[100,200]).values('title','price')
24         # 5 查询所有人民出版社出版的书籍的价格(从高到低排序,去重)
25         res = Book.objects.filter(publish="人民出版社").values('price').distinct().order_by('-price')
26         print('res----------->',res)
27     '''
28     return  render(request, 'book.html',locals())
29 
30 
31 def add_book(request):
32     method = request.method
33     if method == 'POST':
34         req = request.POST
35         title = req['title'].strip()
36         price = req['price'].strip()
37         date = req['date'].strip()
38         publish = req['publish'].strip()
39         if title and price and date and publish:
40             selct_res = Book.objects.filter(title=title)
41             if not selct_res:
42                 Book.objects.create(title=title,price=price,pub_date=date,publish=publish)
43                 return redirect('/app01/book')
44             opt_res = '书籍【%s】已存在,请修改后提交!'%title
45         else:
46             opt_res = '输入不能为空,请修改后提交!'
47     return render(request, 'addbook.html', locals())
48 
49 
50 def update_book(request, num):
51     select_res = Book.objects.filter(id=num)
52     if select_res:
53         method = request.method
54         book_obj = select_res[0]
55         if method == 'POST':
56             req = request.POST
57             title = req['title'].strip()
58             price = req['price'].strip()
59             date = req['date'].strip()
60             publish = req['publish'].strip()
61             if title and price and date and publish:
62                 selct_res = Book.objects.exclude(id=num).filter(title=title)
63                 if not selct_res:
64                     Book.objects.filter(id=num).update(title=title, price=price, pub_date=date, publish=publish)
65                     return redirect('/app01/book')
66                 opt_res = '书籍【%s】已存在,请修改后提交!' % selct_res[0].title
67             else:
68                 opt_res = '输入不能为空,请修改后提交!'
69         return render(request, 'updatebook.html', locals())
70     return redirect('/app01/book')
71 
72 def delete_book(request, num=None):
73     select_res = Book.objects.filter(id=num)
74     if select_res:
75         Book.objects.filter(id=num).delete()
76     return redirect('/app01/book')

 

 

06 django模型层\book\templates\advertise.html

 1 <div class="action">
 2     <div class="panel panel-danger">
 3         <div class="panel-heading">2019进击的菜鸟</div>
 4         <div class="panel-body">
 5             web框架开发
 6         </div>
 7         <div class="panel-body">
 8             crm&爬虫
 9         </div>
10         <div class="panel-body">
11             算法&设计模式&企业应用
12         </div>
13         <div class="panel-body">
14             vue项目
15         </div>
16         <div class="panel-body">
17             复习python&自动化&性能
18         </div>
19     </div>
20     <div class="panel panel-warning">
21         <div class="panel-heading">2020进击的小鸟</div>
22         <div class="panel-body">
23             fighting!
24         </div>
25     </div>
26     <div class="panel panel-success">
27         <div class="panel-heading">2021进击的大鸟</div>
28         <div class="panel-body">
29             go on !
30         </div>
31     </div>
32 </div>
View Code

 

06 django模型层\book\templates\base.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     {% block title %}
 6         <title>base——title</title>
 7     {% endblock title %}
 8     <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
 9           integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
10     {% block style %}
11         <style type="text/css">
12         *{
13             padding: 0;
14             margin:0;
15         }
16         .header{
17             width:100%;
18             height: 50px;
19             background-color: #369;
20         }
21         body{
22             background:#FFF url('/static/base.jpg') repeat-x 0;
23             background-attachment: fixed;
24         }
25     </style>
26     {% endblock style %}
27 
28 </head>
29 <body>
30 
31 <div class="header"></div>
32 
33 <div class="container">
34     <div class="row">
35         <div class="col-md-3">
36             {% include 'advertise.html' %}
37         </div>
38         <div class="col-md-9">
39             {% block content%}
40             <h3>base_content</h3>
41             {% endblock %}
42         </div>
43     </div>
44 </div>
45 
46 </body>
47 {% block js %}
48 <script type="text/javascript" src="/static/jquery-3.3.1.js"></script>
49 {% endblock js %}
50 </html>
View Code

 

06 django模型层\book\templates\book.html

 1 {% extends 'base.html' %}
 2 
 3 {% block style %}
 4     {{ block.super }}
 5     <style>
 6         .mybook {
 7             margin-top: 40px;
 8         }
 9 
10         .btn {
11             margin-top: 5px;
12         }
13         .other{
14             margin-top: 5px;
15         }
16         .filter{
17             margin-bottom: 30px;
18         }
19         .empty{
20             text-align: center;
21             color: #D0D0D0;
22         }
23     </style>
24 {% endblock style %}
25 
26 {% block title %}
27     <title>book</title>
28 {% endblock title %}
29 
30 {% block content %}
31     <h3>查看书籍</h3>
32 
33     <div class="container mybook">
34         <div class="row">
35             <div class="col-md-6">
36                 <form class="form-inline filter" action="">
37                     <div class="form-group">
38                         <div class="form-group other">
39                             <label for="">书籍名称</label>
40                             <input type="text" class="form-control"  placeholder="python" name="title">
41                         </div>
42                     </div>
43                     <button type="submit" class="btn btn-primary">查询</button>
44                 </form>
45                 <a href="/app01/book/add" class="btn btn-primary other">添加书籍</a>
46                 <table class="table table-striped table-bordered">
47                     <thead>
48                     <tr>
49                         <th>书籍名称</th>
50                         <th>价格</th>
51                         <th>出版日期</th>
52                         <th>出版社</th>
53                         <th>删除操作</th>
54                         <th>编辑操作</th>
55                     </tr>
56                     </thead>
57                     <tbody>
58                     {% for book in book_list %}
59                         <tr>
60                             <td>{{ book.title }}</td>
61                             <td>{{ book.price }}</td>
62                             <td>{{ book.pub_date|date:'Y-m-d' }}</td>
63                             <td>{{ book.publish }}</td>
64                             <td><a href="/app01/book/{{ book.pk }}/delete" class="btn btn-danger">删除</a></td>
65                             <td><a href="/app01/book/{{ book.pk }}/update" class="btn btn-info">编辑</a></td>
66                         </tr>
67                         {% empty %}
68                             <td class="empty" colspan="6">暂无数据!</td>
69                     {% endfor %}
70 
71                     </tbody>
72 
73                 </table>
74 
75             </div>
76         </div>
77     </div>
78 {% endblock content %}
View Code

 

06 django模型层\book\templates\addbook.html

 1 {% extends 'base.html' %}
 2 
 3 {% block style %}
 4     {{ block.super }}
 5     <style>
 6         .mybook{
 7             margin-top: 50px;
 8         }
 9         .btn{
10             margin-top: 10px;
11         }
12     .opt_res{
13         margin-top: 50px;
14         color: red;
15     }
16     </style>
17 {% endblock style %}
18 
19 {% block title %}
20     <title>book</title>
21 {% endblock title %}
22 
23 {% block content %}
24     <h3>新增书籍</h3>
25 
26 <div class="container mybook">
27      <div class="row">
28          <div class="col-md-6">
29              <form action="" method="post">
30                  {% csrf_token %}
31                  <div>
32                      <label for="">书籍名称</label>
33                      <input type="text" class="form-control" name="title" value={{ title }}>
34                  </div>
35                  <div>
36                      <label for="">价格</label>
37                      <input type="text" class="form-control" name="price" value={{ price }}>
38                  </div>
39                  <div>
40                      <label for="">出版日期</label>
41                      <input type="date" class="form-control" name="date" value={{ date }}>
42                  </div>
43                  <div>
44                      <label for="">出版社</label>
45                      <input type="text" class="form-control" name="publish" value={{ publish }}>
46                  </div>
47 
48                  <input type="submit" class="btn btn-success pull-right">
49 
50 
51              </form>
52              <p class="opt_res">{{ opt_res }}</p>
53          </div>
54      </div>
55 </div>
56 {% endblock content %}
View Code

 

06 django模型层\book\templates\updatebook.html

 1 {% extends 'base.html' %}
 2 
 3 {% block style %}
 4     {{ block.super }}
 5     <style>
 6         .mybook{
 7             margin-top: 50px;
 8         }
 9         .btn{
10             margin-top: 10px;
11         }
12         .opt_res{
13             margin-top: 50px;
14             color: red;
15         }
16     </style>
17 {% endblock style %}
18 
19 {% block title %}
20     <title>book</title>
21 {% endblock title %}
22 
23 {% block content %}
24     <h3>修改书籍</h3>
25 
26 <div class="container mybook">
27      <div class="row">
28          <div class="col-md-6">
29              <form action="" method="post">
30                  {% csrf_token %}
31                  <div>
32                      <label for="">书籍名称</label>
33                      <input type="text" class="form-control" name="title" value="{{ book_obj.title }}">
34                  </div>
35                  <div>
36                      <label for="">价格</label>
37                      <input type="text" class="form-control" name="price" value="{{ book_obj.price }}">
38                  </div>
39                  <div>
40                      <label for="">出版日期</label>
41                      <input type="date" class="form-control" name="date" value="{{ book_obj.pub_date|date:'Y-m-d' }}">
42                  </div>
43                  <div>
44                      <label for="">出版社</label>
45                      <input type="text" class="form-control" name="publish" value="{{ book_obj.publish }}">
46                  </div>
47 
48                  <input type="submit" class="btn btn-success pull-right">
49 
50 
51              </form>
52              <p class="opt_res">{{ opt_res }}</p>
53          </div>
54      </div>
55 </div>
56 {% endblock content %}
View Code

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!