饮冰三年-人工智能-Python-24 Django ORM增删改查
一:首先使用默认的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/
""" 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': '12qwaszx!@QWASZX', #你的数据库密码
'HOST': '', #你的数据库主机,留空默认为localhost
'PORT': '', #你的数据库端口 } } # 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/'
Setting.py
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=,pub_date="2012-12-12",author="张三")
b.save()
# 方式二
Book.objects.create(name="Linux",price=,author="李四",pub_date="2011-11-11")
return HttpResponse("添加成功!")
def updatebook(request):
# 方式一
Book.objects.filter(author="李四").update(price=)
# 方式二
b=Book.objects.get(id=)
b.price=
b.save()
return HttpResponse("修改成功!")
def deltebook(request):
Book.objects.filter(id=).delete()
return HttpResponse("删除成功!")
def querybook(request):
# ----------返回的是个集合 <class 'django.db.models.query.QuerySet'>----------
# bookList=Book.objects.all()# 查询所有结果
# bookList=Book.objects.all()[:]# 查询结果 支持切片
# bookList = Book.objects.filter(author='张三')#它包含了与所给筛选条件相匹配的对象
# bookList = Book.objects.all().exclude(author='张三')#它包含了与所给筛选条件不匹配的对象
# ----------like------------返回的是个集合 <class 'django.db.models.query.QuerySet'>----------
# bookList = Book.objects.filter(id__lte=,id__gt=) # 查询所有结果 <id<=
# bookList = Book.objects.filter(id__range=[,]) # 查询所有结果 between and
# bookList = Book.objects.filter(id__in=(,)) # 查询所有结果 in
# bookList = Book.objects.exclude(id__in=(,)) # 查询所有结果 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=) # 返回与所给筛选条件相匹配的对象,返回结果有且只有一个,如果符合筛选条件的对象超过一个或者没有都会抛出错误
# 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="")
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())
五、通过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="")
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(xud0@7nditgvoch%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': '12qwaszx!@QWASZX', # 你的数据库密码
'HOST': '', # 你的数据库主机,留空默认为localhost
'PORT': '', # 你的数据库端口 }
} # 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
六、 总结
一、必知必会13条
1:返回具体对象
get() first() last()
2:返回QuerySet
all() , filter() , exclude() , order_by() , reverse() , distinct()
3:返回指定字段的QuerySet
values() values_list()
4:返回数字
count()
5:返回布尔值
exists()
二、单表中双下划线
__gt # greater than 大于
__lt # less than 小于
__gte # greater than equal 大于等于
__lte #小于等于
_in # in
__range # 什么范围
__contains # like 包含
__startswith # 以什么开头
__endswith # 以什么结束
__isnull=True # 是否为空
__year # 年
__month # 月
三、高级操作
aggregate #聚合
annotate #分组
F 和 Q
事务
饮冰三年-人工智能-Python-24 Django ORM增删改查的更多相关文章
- django ORM 增删改查 模糊查询 字段类型 及参数等
ORM 相关 #sql中的表 #创建表: CREATE TABLE employee( id INT PRIMARY KEY auto_increment , name VARCHAR (), gen ...
- Django框架(三)—— orm增删改查、Django生命周期
目录 orm增删改查.Django生命周期 一.orm介绍 二.orm增删改字段 三.Django生命周期 orm增删改查.Django生命周期 一.orm介绍 1.什么是orm ORM即Object ...
- python操作mysql数据库增删改查的dbutils实例
python操作mysql数据库增删改查的dbutils实例 # 数据库配置文件 # cat gconf.py #encoding=utf-8 import json # json里面的字典不能用单引 ...
- ORM增删改查并发性能测试2
前言 上一篇<ORM增删改查并发性能测试>出现了点小失误,有的输出SQL日志的代码没有禁用,数据库连接字符串可能有问题.统一环境,统一代码后,重新写一篇. 这次重点是并发性能测试,真不是为 ...
- 饮冰三年-人工智能-Python-26 Django 学生管理系统
背景:创建一个简单的学生管理系统,熟悉增删改查操作 一:创建一个Django项目(http://www.cnblogs.com/wupeiqi/articles/6216618.html) 1:创建实 ...
- $Django orm增删改字段、建表 ,单表增删改查,Django请求生命周期
1 orm介绍 ORM是什么 ORM 是 python编程语言后端web框架 Django的核心思想,“Object Relational Mapping”,即对象-关系映射,简称ORM. 一 ...
- Django框架(三)-- orm增删改查、Django生命周期
一.orm介绍 1.什么是orm ORM即Object Relational Mapping,全称对象关系映射. 2.使用orm的优缺点 优点: 不用写SQL语句 开发效率高 缺点: SQL的效率低 ...
- Django 自带的ORM增删改查
通过Django来对数据库进行增删改查 1 首先创建类,在app应用程序里面的model模块里面创建类,写好数据库信息,方便我们待会初始化: 2 创建在django项目里面的settings里面添加 ...
- day054 组件 CBV FBV 装饰器 ORM增删改查
组件: 把一小段HTML 放在一个HTML中 nav.html 使用: {% include ‘nav.html ’ %} 一. FBV 和CBV 1.FBV(function base ...
随机推荐
- Python项目部署-使用Nginx部署Django项目
一.nginx介绍及部署 二.nginx部署路飞学城代码 nginx配置安装 同样,nginx也有很多的安装方式: 1)源码安装(运维偏向:规范,便于配置管理) 2)yum,rpm安装(为了效率可以选 ...
- webservice异常
webservice的一个常见异常: [SOAPException: faultCode=SOAP-ENV:Client; msg=Error parsing HTTP status line &qu ...
- Activiti工作流框架——快速上手
一.前言 最近在做公司的OA,里面有用到工作流,公司用的是 jbpm4,感觉比较老,资料有点少,就先学学 新一点的 activiti ㄟ(▔▽▔)ㄏ 首先工作流的概念是:工作流(Workfl ...
- [OI]Noip 2018总结(普及)
考砸了,还有原谅我代码十分有限的可读性. 一个人的真正伟大之处就在于他能够认识到自己的渺小.——保罗 从一年前初一九月到现在18年10月接触OI已经有一年了.几次模拟赛也自我感觉良好,都过了一等的线, ...
- Java【第十篇】集合
Java 集合概述 Java 集合就像一种容器,可以把多个对象的引用放入容器中.Java 集合类可以用于存储数量不等的多个对象,还可用于保存具有映射关系的关联数组Java 集合可分为 Set.List ...
- Super Mario HDU - 4417 (主席树)
Mario is world-famous plumber. His “burly” figure and amazing jumping ability reminded in our memory ...
- nuxt.js实战之移动端rem
nuxt.js的项目由于是服务端渲染,通过js动态调整不同尺寸设备的根字体这种rem方案存在一种缺陷.由于设置字体的代码不能做服务端渲染,导致服务端返回的代码一开始没有相应的跟字体,直到与前端代码进行 ...
- 礼物(中国剩余定理+拓展gcd求逆元+分治=拓展Lucus)
礼物 题意: 求\[C(n,m)\ \%\ p\] \(n,m,p\le 10^9\),且若\(p=\prod_{i=1}^{k}{p_i}^{c_i}\),则\(\forall i\in [1..k ...
- centos7下tomcat8.5安装部署与优化
转自:https://www.cnblogs.com/busigulang/articles/8529719.html centos 7 Tomcat 8.5 的安装及生产环境的搭建调优 一 安装to ...
- 四大解析器(BeautifulSoup、PyQuery、lxml、正则)性能比较
用标题中的四种方式解析网页,比较其解析速度.当然比较结果数值与电脑配置,python版本都有关系,但总体差别不会很大. 下面是我的结果,lxml xpath最快,bs4最慢 ==== Python v ...