博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
09 django模型层_单表练习
阅读量:4695 次
发布时间:2019-06-09

本文共 13762 字,大约阅读时间需要 45 分钟。

模型层(单表练习)

图书管理系统:

实现功能: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 # Internationalization106 # https://docs.djangoproject.com/en/2.2/topics/i18n/107 108 LANGUAGE_CODE = 'en-us'109 110 TIME_ZONE = 'UTC'111 112 USE_I18N = True113 114 USE_L10N = True115 116 USE_TZ = True117 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 # 端口 默认3306135 }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 pymysqlpymysql.install_as_MySQLdb()

 

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

from django.contrib import adminfrom django.urls import path,re_path,includeurlpatterns = [    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,includefrom book_app01 import viewsurlpatterns = [    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.GET10     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.method33     if method == 'POST':34         req = request.POST35         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】已存在,请修改后提交!'%title45         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.method54         book_obj = select_res[0]55         if method == 'POST':56             req = request.POST57             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].title67             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 
2
3
2019进击的菜鸟
4
5 web框架开发 6
7
8 crm&爬虫 9
10
11 算法&设计模式&企业应用12
13
14 vue项目15
16
17 复习python&自动化&性能18
19
20
21
2020进击的小鸟
22
23 fighting!24
25
26
27
2021进击的大鸟
28
29 go on !30
31
32
View Code

 

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

1  2  3  4     
5 {% block title %} 6 base——title 7 {% endblock title %} 8
10 {% block style %}11 26 {% endblock style %}27 28 29 30 31
32 33
34
35
36 {% include 'advertise.html' %}37
38
39 {% block content%}40

base_content

41 {% endblock %}42
43
44
45 46 47 {% block js %}48 49 {% endblock js %}50
View Code

 

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

1 {% extends 'base.html' %} 2  3 {% block style %} 4     {
{ block.super }} 5 24 {% endblock style %}25 26 {% block title %}27 book28 {% endblock title %}29 30 {% block content %}31

查看书籍

32 33
34
35
36
37
38
39
40
41
42
43
44
45
添加书籍46
47
48
49
50
51
52
53
54
55
56
57
58 {% for book in book_list %}59
60
61
62
63
64
65
66
67 {% empty %}68
69 {% endfor %}70 71
72 73
书籍名称 价格 出版日期 出版社 删除操作 编辑操作
{ { book.title }} { { book.price }} { { book.pub_date|date:'Y-m-d' }} { { book.publish }} 删除 编辑
暂无数据!
74 75
76
77
78 {% endblock content %}
View Code

 

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

1 {% extends 'base.html' %} 2  3 {% block style %} 4     {
{ block.super }} 5 17 {% endblock style %}18 19 {% block title %}20 book21 {% endblock title %}22 23 {% block content %}24

新增书籍

25 26
27
28
29
30 {% csrf_token %}31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 48
49 50 51
52

{

{ opt_res }}

53
54
55
56 {% endblock content %}
View Code

 

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

1 {% extends 'base.html' %} 2  3 {% block style %} 4     {
{ block.super }} 5 17 {% endblock style %}18 19 {% block title %}20 book21 {% endblock title %}22 23 {% block content %}24

修改书籍

25 26
27
28
29
30 {% csrf_token %}31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 48
49 50 51
52

{

{ opt_res }}

53
54
55
56 {% endblock content %}
View Code

 

转载于:https://www.cnblogs.com/znyyy/p/11319794.html

你可能感兴趣的文章
实现自动点击
查看>>
MVP开发模式的理解
查看>>
Unity多开的方法
查看>>
File类中的list()和listFiles()方法
查看>>
我的VS CODE插件配置 主要针对.NET和前端插件配置
查看>>
关于js中的事件
查看>>
一致性哈希算法运用到分布式
查看>>
决策树和随机森林->信息熵和条件熵
查看>>
iOS10 UI教程视图和子视图的可见性
查看>>
Maven学习笔记
查看>>
FindChildControl与FindComponent
查看>>
1、简述在java网络编程中,服务端程序与客户端程序的具体开发步骤?
查看>>
C# Web版报表
查看>>
中国城市json
查看>>
android下载手动下载Android SDK
查看>>
北京邮电大学 程序设计课程设计 电梯 文件输入版本(已调试,大致正确运行==)...
查看>>
C++学习:任意合法状态下汉诺塔的移动(原创)
查看>>
学霸修炼的秘籍
查看>>
Duplicate 复制数据库 搭建Dataguard
查看>>
leetcode133 - Clone Graph - medium
查看>>