飲冰三年-人工智慧-Python-24 Django ORM增刪改查
阿新 • • 發佈:2018-12-19
一:首先使用預設的sqlite3建立表
1:現在在models.py中新增表模型
from django.db import models # Create your models here. class Book(models.Model): name=models.CharField(max_length=20) price = models.IntegerField() pub_date=models.DateField()models.py
2:在Teminal中通過命令建立表
python manage.py makemigrations ----------該命令執行後會在migrations中建立0001_initial.py中生成檔案
python manage.py migrate ----------該命令執行後會在資料庫中生成資料表
至此,資料庫建立成功
二:使用Mysql建立表
1:修改配置表
""" Django settings for Django_ORM project. Generated by 'django-admin startproject' using Django 2.1.4. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/Setting.py""" import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret!SECRET_KEY = '(%h695j&g^4s(@&hk9#66xye6nrv=y9hr*(1va58(^j%_zmlzw' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01.apps.App01Config', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Django_ORM.urls' 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', ], }, }, ] WSGI_APPLICATION = 'Django_ORM.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'Django_ORM', #你的資料庫名稱 'USER': 'root', #你的資料庫使用者名稱 'PASSWORD': '[email protected]', #你的資料庫密碼 'HOST': '', #你的資料庫主機,留空預設為localhost 'PORT': '3306', #你的資料庫埠 } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/'
2:修改Django_ORM下面的__init__.py檔案 (python的資料庫驅動引擎,把預設的MySQLdb()替換成pymysql)
如果事先沒有安裝pymysql模組 可通過 pip install pymysql命令安裝
import pymysql # (python的資料庫驅動引擎,把預設的MySQLdb()替換成pymysql) pymysql.install_as_MySQLdb()__init__.py
3:繼續執行以下命令
python manage.py makemigrations ----------該命令執行後會在migrations中建立0001_initial.py中生成檔案
python manage.py migrate ----------該命令執行後會在資料庫中生成資料表
至此,資料表建立成功
三、通過orm對錶進行增刪改查
在settings加上日誌記錄部分,就可以方便的看出每條操作所執行的SQL語句了
LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'propagate': True, 'level':'DEBUG', }, } }LOGGING
1:建立首頁
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{ margin: 0px; padding: 0px; } .head{ line-height: 40px; background-color: green; color: white; text-align: center; } </style> </head> <body> <div class="outer"> <div class="head">標題</div> <div class="content"> <a href="/addbook/">新增書籍</a> <a href="/updatebook/">修改書籍</a> <a href="/deltebook/">刪除書籍</a> </div> <div></div> </div> </body> </html>index.html
2:設定對應urls
"""Django_ORM URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index,name="index"), #建立首頁 path('addbook/', views.addbook,name="addbook"), #新增書籍 path('updatebook/', views.updatebook, name="updatebook"), # 新增書籍 path('deltebook/', views.deltebook, name="deltebook"), # 新增書籍 ]urls.py
3:views
from django.shortcuts import render,HttpResponse from app01.models import * # Create your views here. def index(request): return render(request,"index.html") def addbook(request): # 方式一 b=Book(name="python",price=80,pub_date="2012-12-12",author="張三") b.save() # 方式二 Book.objects.create(name="Linux",price=99,author="李四",pub_date="2011-11-11") return HttpResponse("新增成功!") def updatebook(request): # 方式一 Book.objects.filter(author="李四").update(price=999) # 方式二 b=Book.objects.get(id=2) b.price=888 b.save() return HttpResponse("修改成功!") def deltebook(request): Book.objects.filter(id=1).delete() return HttpResponse("刪除成功!")views
from django.shortcuts import render,HttpResponse from app01.models import * # Create your views here. def index(request): return render(request,"index.html") def addbook(request): # 方式一 b=Book(name="python",price=80,pub_date="2012-12-12",author="張三") b.save() # 方式二 Book.objects.create(name="Linux",price=99,author="李四",pub_date="2011-11-11") return HttpResponse("新增成功!") def updatebook(request): # 方式一 Book.objects.filter(author="李四").update(price=999) # 方式二 b=Book.objects.get(id=2) b.price=888 b.save() return HttpResponse("修改成功!") def deltebook(request): Book.objects.filter(id=1).delete() return HttpResponse("刪除成功!") def querybook(request): # ----------返回的是個集合 <class 'django.db.models.query.QuerySet'>---------- # bookList=Book.objects.all()# 查詢所有結果 # bookList=Book.objects.all()[:2]# 查詢結果 支援切片 # bookList = Book.objects.filter(author='張三')#它包含了與所給篩選條件相匹配的物件 # bookList = Book.objects.all().exclude(author='張三')#它包含了與所給篩選條件不匹配的物件 # ----------like------------返回的是個集合 <class 'django.db.models.query.QuerySet'>---------- # bookList = Book.objects.filter(id__lte=5,id__gt=2) # 查詢所有結果 2<id<=5 # bookList = Book.objects.filter(id__range=[1,4]) # 查詢所有結果 between and # bookList = Book.objects.filter(id__in=(1,2)) # 查詢所有結果 in # bookList = Book.objects.exclude(id__in=(1,2)) # 查詢所有結果 not in # bookList = Book.objects.filter(name__contains="lin") # # bookList = Book.objects.filter(name__icontains="lin") # 忽略大小寫 # bookList = Book.objects.filter(name__startswith="lin") # # bookList = Book.objects.filter(name__istartswith="lin") # 忽略大小寫 # bookList = Book.objects.filter(name__endswith="A") # bookList = Book.objects.filter(name__iendswith="A") # 忽略大小寫 # ----------返回的是個物件 <class 'app01.models.Book'>---------- # aBook = Book.objects.get(id=5) # 返回與所給篩選條件相匹配的物件,返回結果有且只有一個,如果符合篩選條件的物件超過一個或者沒有都會丟擲錯誤 # aBook = Book.objects.first() # 返回第一條記錄 # aBook = Book.objects.last() # 返回最後一條記錄 # ----------對返回結果進行處理---------- # bookList = Book.objects.all().values("name","author") #只篩選“書名”和“作者” # bookList = Book.objects.all().values_list("name", "author") #它與values()非常相似,它返回的是一個元組序列,values返回的是一個字典序列 <QuerySet [('python', '張三'), ('Linux', '李四'), ('Java', '張三2'), ('Linux2', '李四')]> # bookList = Book.objects.all().order_by("price","id") #排序 # bookList = Book.objects.all().reverse()#對查詢結果反向排序,貌似沒什麼用 # bookList = Book.objects.all().values("author").distinct()#從返回結果中剔除重複紀錄 # num=Book.objects.all().count()# 返回資料庫中匹配查詢(QuerySet)的物件數量。 # num = Book.objects.filter(author='張三111').exists()# 如果QuerySet包含資料,就返回True,否則返回False。 return render(request,"index.html",locals())查詢
四、通過orm對錶進行增刪改查之一對多
from django.shortcuts import render,HttpResponse from APP2.models import * # Create your views here. def index(request): return render(request,"index.html") def addbook(request): # 方式一,通過ID儲存 b=Book(name=".net",price=80,pub_date="2012-12-12",publish_id="1") b.save() # 方式二,先獲取“出版社”實體,再儲存 pub=Publish.objects.get(id=1) Book.objects.create(name="Linux",price=99,pub_date="2011-11-11",publish=pub) return HttpResponse("新增成功!") def updatebook(request): # 方式一 更改“清華出版社”下所有書的價格 Book.objects.filter(publish__name="清華出版社").update(price=999) # 方式二 更改id為2的書的出版社名稱 b=Book.objects.filter(id=2)[0].publish b.name="新華出版社" b.save() return HttpResponse("修改成功!") def deltebook(request): Book.objects.filter(publish__name="新華出版社").delete() return HttpResponse("刪除成功!") def querybook(request): # 獲取某出版社出版的書 # ----------方式1:先獲取某出版社--->再獲取對應的書---------- # pu=Publish.objects.filter(name="北京大學出版社")[0] # bookList=Book.objects.filter(publish=pu) # ----------方式2---------- # bookList = Publish.objects.get(id=1).book_set.all() # ----------方式3-雙下劃線---------- bookList = Book.objects.filter(publish__name="北京大學出版社") # 練習:查詢某書的出版社名稱 publishName =Book.objects.filter(name="python").values_list("publish__name")[0] publishName=Publish.objects.filter(book__name="python").values_list("name")[0] return render(request,"index.html",locals())View Code
五、通過orm對錶進行增刪改查之多對多
from django.db import models class Book(models.Model): name=models.CharField(max_length=20) price = models.IntegerField() pub_date=models.DateField() # 建立一對多的方法 publish = models.ForeignKey("Publish",on_delete=models.CASCADE) # 建立多對多的方法 authors=models.ManyToManyField("Author") class Publish(models.Model): name = models.CharField(max_length=32) city = models.CharField(max_length=32) class Author(models.Model): name=models.CharField(max_length=32) age=models.IntegerField()多對多
from django.db import models class Book(models.Model): name=models.CharField(max_length=20) price = models.IntegerField() pub_date=models.DateField() # 建立一對多的方法 publish = models.ForeignKey("Publish",on_delete=models.CASCADE) # 建立多對多的方法 authors=models.ManyToManyField("Author") class Publish(models.Model): name = models.CharField(max_length=32) city = models.CharField(max_length=32) class Author(models.Model): name=models.CharField(max_length=32) age=models.IntegerField()models
from django.shortcuts import render,HttpResponse from django.db.models import Avg,Max,Sum,Min,F,Q from APP2.models import * # Create your views here. def index(request): return render(request,"index.html") def addbook(request): # 方式一,通過ID儲存 b=Book(name=".net",price=80,pub_date="2012-12-12",publish_id="1") b.save() # 方式二,先獲取“出版社”實體,再儲存 pub=Publish.objects.get(id=1) Book.objects.create(name="Linux",price=99,pub_date="2011-11-11",publish=pub) return HttpResponse("新增成功!") def updatebook(request): # 方式一 更改“清華出版社”下所有書的價格 Book.objects.filter(publish__name="清華出版社").update(price=999) # 方式二 更改id為2的書的出版社名稱 b=Book.objects.filter(id=2)[0].publish b.name="新華出版社" b.save() return HttpResponse("修改成功!") def deltebook(request): Book.objects.filter(publish__name="新華出版社").delete() return HttpResponse("刪除成功!") def querybook(request): # 獲取某出版社出版的書 # ----------方式1:先獲取某出版社--->再獲取對應的書---------- # pu=Publish.objects.filter(name="北京大學出版社")[0] # bookList=Book.objects.filter(publish=pu) # ----------方式2---------- # bookList = Publish.objects.get(id=1).book_set.all() # ----------方式3-雙下劃線---------- bookList = Book.objects.filter(publish__name="北京大學出版社") # 練習:查詢某書的出版社名稱 publishName =Book.objects.filter(name="python").values_list("publish__name")[0] publishName=Publish.objects.filter(book__name="python").values_list("name")[0] return render(request,"index.html",locals()) def addAuthorForBook(request): # -------------------多對多開始------------------------ # 給書籍新增作者2 3 ---新增一個集合 book_obj = Book.objects.get(id=7) # 先獲取到某本書 author_obj = Author.objects.filter(id__in=(2,3)) # 獲取作者 2 3 book_obj.authors.add(*author_obj) # 給書新增作者----新增一個集合 # 給書籍新增作者4 ---新增一個實體 book_obj.authors.add(Author.objects.get(id=4)) return HttpResponse("為書籍新增作者成功!") def updateAuthorForBook(request): # -------------------多對多開始------------------------ # 直接在author表中修改名字 b=Book.objects.get(id=7).authors.all()[0] b.name="李師師" b.save() return HttpResponse("為書籍修改作者成功!") def deleteAuthorForBook(request): # -------------------多對多開始------------------------ # 移除作者3 book_obj = Book.objects.get(id=7) # 先獲取到某本書 book_obj.authors.remove(3) # 可以進行簡寫 #可移除多個 author_obj = Author.objects.filter(id=2) book_obj.authors.remove(*author_obj) return HttpResponse("為書籍刪除作者成功!") def queryAuthorForBook(request): # -------------------多對多開始------------------------ #查詢張三出過的書 bookList = Book.objects.filter(authors__name="張三") #查詢書本的平均價格 booksAvgPrice=Book.objects.all().aggregate(Avg("price")) # 查詢"張三"書的總價格 booksSumPrice = Book.objects.filter(authors__name="張三").aggregate(總價格=Sum("price")) # 求每個人出書的平均價格 booksAvgPriceForPeople=Book.objects.values("authors__name").annotate(price=Avg("price")) # 求各個出版社的最低的價格 booksPublishMinPrice=Book.objects.values("publish__name").annotate(minprice=Min("price")) return render(request,"index.html",locals()) def updatePriceForBook(request): Book.objects.all().update(price=F("price")+10) return HttpResponse("為書籍添加價格成功!") def queryPriceForBook(request): # -------------------多對多開始------------------------ #查詢張三出過的書,並且價格等於90(Q查詢和普通查詢一起使用的時候,Q放前面) bookList2 = Book.objects.filter(Q(price=90),authors__name="張三") # 查詢張三出過的書,或者價格等於90 bookList2 = Book.objects.filter(Q(price=90)|Q(authors__name="張三")).values("id","name","authors__name","price") # 查詢不是張三出過的書 bookList2 = Book.objects.filter(~Q(authors__name="張三")) #-------------------注意:bookList2為QuerySet型別,懶載入,不使用不會請求資料庫--------------- # -------------------為了減少記憶體中的快取可使用-------------------------- if bookList2.exists(): print("不想向記憶體中新增資料,僅僅是判斷是否存在") #-------------------迭代器-------------------------- bookList2=bookList2.iterator() for ite in bookList2: print("轉換成迭代器以後,用一次就沒有了") return render(request,"index.html",locals())Views
"""Django_ORM2 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from APP2 import views urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index,name="index"), #建立首頁 path('addbook/', views.addbook,name="addbook"), #新增書籍 path('updatebook/', views.updatebook, name="updatebook"), # 新增書籍 path('deltebook/', views.deltebook, name="deltebook"), # 新增書籍 path('querybook/', views.querybook, name="querybook"), # 新增書籍 path('addAuthorForBook/', views.addAuthorForBook, name="addAuthorForBook"), # 給書籍新增作者 path('updateAuthorForBook/', views.updateAuthorForBook, name="updateAuthorForBook"), # 修改書籍的作者 path('deleteAuthorForBook/', views.deleteAuthorForBook, name="deleteAuthorForBook"), # 刪除書籍的作者 path('queryAuthorForBook/', views.queryAuthorForBook, name="queryAuthorForBook"), # 查詢書籍的作者 path('updatePriceForBook/', views.updatePriceForBook, name="updatePriceForBook"), # 給書籍新增10元 path('queryPriceForBook/', views.queryPriceForBook, name="queryPriceForBook"), # Q查詢 ]urls
""" Django settings for Django_ORM2 project. Generated by 'django-admin startproject' using Django 2.1.4. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '5%@&gx+jf88o2([email protected]%p6#+8e)dx$s7g6n5jdj^' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'APP2.apps.App2Config', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Django_ORM2.urls' 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', ], }, }, ] WSGI_APPLICATION = 'Django_ORM2.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'Django_ORM', # 你的資料庫名稱 'USER': 'root', # 你的資料庫使用者名稱 'PASSWORD': '[email protected]', # 你的資料庫密碼 'HOST': '', # 你的資料庫主機,留空預設為localhost 'PORT': '3306', # 你的資料庫埠 } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'propagate': True, 'level':'DEBUG', }, } }settings
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{ margin: 0px; padding: 0px; } .head{ line-height: 40px; background-color: green; color: white; text-align: center; } </style> </head> <body> <div class="outer"> <div class="head">標題</div> <div class="content"> <a href="/addbook/">新增書籍</a> <a href="/updatebook/">修改書籍</a> <a href="/deltebook/">刪除書籍</a> <a href="/querybook/">查詢書籍</a> <br/> <a href="/addAuthorForBook/">給書籍新增作者</a> <a href="/updateAuthorForBook/">修改書籍的作者</a> <a href="/deleteAuthorForBook/">刪除書籍的作者</a> <a href="/queryAuthorForBook/">查詢書籍的作者</a> <br/> <a href="/updatePriceForBook/">給書籍新增10元(F查詢)</a> <a href="/queryPriceForBook/">查詢書籍(Q查詢)</a> </div> <div> {% if bookList.count > 0 %} <table> <tr><td>序號</td><td>書名</td><td>作者</td><td>價格</td></tr> {% for book in bookList %} <tr><td>{{ book.id }}</td><td>{{ book.name }}</td><td>暫無</td><td>{{ book.price }}</td></tr> {% endfor %} </table> {% endif %} 查詢出一本書所在的出版社:{{ publishName }} <br/> 返回數字:{{ num }} <br/> 多對多查詢 <br/> 書的平均價格:{{ booksAvgPrice }} <br/> 書的總價格:{{ booksSumPrice }} <br/> {% if booksAvgPriceForPeople.count > 0 %} <table> <tr><td>作者</td><td>價格</td></tr> {% for authorPrice in booksAvgPriceForPeople %} <tr> <td>{{ authorPrice.authors__name }}</td><td>{{ authorPrice.price }}</td></tr> {% endfor %} </table> {% endif %} <br/> {% if booksPublishMinPrice.count > 0 %} <table> <tr><td>出版社</td><td>最低價格</td></tr> {% for publishPrice in booksPublishMinPrice %} <tr> <td>{{ publishPrice.publish__name}}</td><td>{{ publishPrice.minprice }}</td></tr> {% endfor %} </table> {% endif %} <br/> {% if bookList2.count > 0 %} <table> <tr><td>序號</td><td>書名</td><td>作者</td><td>價格</td></tr> {% for book in bookList2 %} <tr><td>{{ book.id }}</td><td>{{ book.name }}</td><td>{{ book.authors__name }}</td><td>{{ book.price }}</td></tr> {% endfor %} </table> {% endif %} </div> </div> </body> </html>index.html