Django之ORM查询
ORM
映射关系:
表名 <-------> 类名 字段 <-------> 属性 表记录 <------->类实例对象
图书管理系统的增删改查:
代码如下:
views
from django.shortcuts import render ,HttpResponse,redirect from app01 import models # Create your views here. def index(request): # 从数据库取出所有书籍对象 bookList=models.Book.objects.all() # QuerySet数据类型 [bookObj1,.....] return render(request,"index.html",{"bookList":bookList}) def delBook(request,id): models.Book.objects.filter(nid=id).delete()#删除数据库里的数据 return redirect("/index/") def editBook(request): if request.method=="POST":
id=request.POST.get("book_id")#获取form表单的数据用这个种方式 # 修改方式1:save(效率低)不推荐使用
# book_obj=models.Book.objects.filter(nid=id)[0]
# book_obj.title="金平"
# book_obj.save() # 修改方式2:
title=request.POST.get("title")
author=request.POST.get("author")
pubDate=request.POST.get("pubDate")
price=request.POST.get("price") models.Book.objects.filter(nid=id).update(title=title,author=author,publishDate=pubDate,price=price) return redirect("/index/") id = request.GET.get("book_id")
print("id", id)
edit_book=models.Book.objects.filter(nid=id)[0] # [obj1,] QuerySet数据类型 return render(request,"edit.html",{"edit_book":edit_book}) def addBook(request):
if request.method=="POST":
title=request.POST.get("title")
author=request.POST.get("author")
pubDate=request.POST.get("pubDate")
price=request.POST.get("price") # 添加数据库
# 方式1:用save时要先实例化一个对象,接着在保存
# book_obj=models.Book(title=title,author=author,publishDate=pubDate,price=price)
# book_obj.save() #方式2用create的话直接就能保存了,返回的就是保存的值
book_obj=models.Book.objects.create(title=title,author=author,publishDate=pubDate,price=price)
print(book_obj.title,book_obj.nid) return redirect("/index/") return render(request,"addBook.html") def query(request):
# 查询方法API: #1 all: models.表名.objects.all() book_all=models.Book.objects.all() # 结果是querySet集合 [model对象,....]
#print(book_all) # <QuerySet [<Book: Book object>, <Book: Book object>, <Book: Book object>]> # 2 filter: models.表名.objects.filter() # 结果是querySet集合 [model对象,....] # ret1=models.Book.objects.filter(author="yuan") # # <QuerySet [<Book: 追风筝的人>, <Book: asd>]>
#ret2=models.Book.objects.filter(nid=1) # <QuerySet [<Book: yuan>]>
# ret2=models.Book.objects.filter(author="yuan",price=123) # <QuerySet [<Book: yuan>]>
# print(ret2) # 3 get models.表名.objects.get() # model对象 # ret3=models.Book.objects.get(author="yuan")
# print(ret3.price) # exclude : 排除条件
# ret4=models.Book.objects.exclude(author="yuan")
# print(ret4) # values方法
# ret=models.Book.objects.filter(author="yuan").values("title","price")#获得是字典
# print(ret)# <QuerySet [{'title': '追风筝的人', 'price': Decimal('99.00')}, {'title': 'asd', 'price': Decimal('123.00')}]> # ret = models.Book.objects.filter(author="yuan").values_list("title", "price")#拿到的是元祖
# print(ret) # <QuerySet [('追风筝的人', Decimal('99.00')), ('asd', Decimal('123.00'))]> # ret=models.Book.objects.filter(author="yuan").values("author").distinct()#去重
# print(ret) # count方法
# ret=models.Book.objects.filter(author="yuan").count()#计数
# print(ret) # first 方法
# ret = models.Book.objects.all().first()#第一个
# print(ret) # exists方法
# if models.Book.objects.all().exists():是否存在
# print("exists")
# else:
# print("nothing") ret=models.Book.objects.filter(price__gt=100)#小于
ret=models.Book.objects.filter(price__gte=99) # 大于等于 #ret=models.Book.objects.filter(publishDate__year=2017,publishDate__month=10)查询日期的
#ret=models.Book.objects.filter(author__startswith="张")#以什么开头 print(ret)
return HttpResponse("OK")
视图函数代码
model代码
from django.db import models # Create your models here. class Book(models.Model):
nid = models.AutoField(primary_key=True)
title = models.CharField(max_length=32)
author = models.CharField(max_length=32)
publishDate = models.DateField()
price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.title #这是类的方法
Template代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title> <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css">
<script src="/static/bootstrap-3.3.7/js/bootstrap.min.js"></script>
<style>
.container{
margin-top: 100px;
}
</style>
</head>
<body> <div class="container">
<div class="row">
<div class="col-md-6 col-lg-offset-3">
<a href="/addBook/"><button class="btn btn-primary">添加书籍</button></a>
<table class="table table-striped">
<thead>
<tr>
<th>编号</th>
<th>书名</th>
<th>作者</th>
<th>出版日期</th>
<th>价格</th>
<th>操作</th>
</tr>
</thead> <tbody>
{% for book_obj in bookList %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ book_obj.title }}</td>
<td>{{ book_obj.author }}</td>
<td>{{ book_obj.publishDate|date:"Y-m-d"}}</td>
<td>{{ book_obj.price }}</td>
<td>
<a href="/del/{{ book_obj.nid }}"><button class="btn btn-danger">删除</button></a>
<a href="/edit/?book_id={{ book_obj.nid }}"><button class="btn btn-info">编辑</button></a>
{# <a href="/edit/{{ book_obj.nid }}"><button class="btn btn-info">编辑</button></a>#}方法一
</td> </tr>
{% endfor %} </tbody>
</table>
</div>
</div>
</div> </body>
</html>
index
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
</head>
<body> <h3>编辑页面</h3> <form action="/edit/" method="post"><!--如果edit路径里没有编号,就用一个type=hidden来传递-->
{% csrf_token %}<!--这个是保证通过django的安全认证的-->
<p><input type="hidden" name="book_id" value="{{ edit_book.nid }}"></p>
<p>书名 <input type="text" name="title" value="{{ edit_book.title }}"></p>
<p>作者 <input type="text" name="author" value="{{ edit_book.author }}"></p>
<p>出版日期 <input type="date" name="pubDate" value="{{ edit_book.publishDate|date:'Y-m-d'}}"></p>
<p>价格 <input type="text" name="price" value="{{ edit_book.price }}"></p>
<p> <input type="submit"></p>
</form> </body>
</html>
edit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
</head>
<body> <h3>添加书籍:</h3>
<form action="/addBook/" method="post">
{% csrf_token %}
<p>书名 <input type="text" name="title"></p>
<p>作者 <input type="text" name="author"></p>
<p>出版日期 <input type="date" name="pubDate"></p>
<p>价格 <input type="text" name="price"></p>
<p> <input type="submit"></p>
</form> </body>
</html>
查询表记录的方法:
查询相关API
<1> all(): 查询所有结果这个是 QuerySet集合
<2> filter(**kwargs): 它包含了与所给筛选条件相匹配的对象 QuerySet集合 只能查且的条件不能查or的条件
<3> get(**kwargs): 返回与所给筛选条件相匹配的对象,返回结果有且只有一个, 这个是object对象
如果符合筛选条件的对象超过一个或者没有都会抛出错误。
<5> exclude(**kwargs): 它包含了与所给筛选条件不匹配的对象 QuerySet集合
<4> values(*field): 返回一个ValueQuerySet——一个特殊的QuerySet,运行后得到的并不是一系列
model的实例化对象,而是一个可迭代的字典序列
<9> values_list(*field): 它与values()非常相似,它返回的是一个元组序列,values返回的是一个字典序列
<6> order_by(*field): 对查询结果排序
<7> reverse(): 对查询结果反向排序
<8> distinct(): 从返回结果中剔除重复纪录
<10> count(): 返回数据库中匹配查询(QuerySet)的对象数量。
<11> first(): 返回第一条记录
<12> last(): 返回最后一条记录
<13> exists(): 如果QuerySet包含数据,就返回True,否则返回False
注意:一定区分object与querySet的区别 !!!
双下划线之单表查询
models.Tb1.objects.filter(id__lt=10, id__gt=1) # 获取id大于1 且 小于10的值
models.Tb1.objects.filter(id__in=[11, 22, 33]) # 获取id等于11、22、33的数据
models.Tb1.objects.exclude(id__in=[11, 22, 33]) # not in
models.Tb1.objects.filter(name__contains="ven")
models.Tb1.objects.filter(name__icontains="ven") # icontains大小写不敏感
models.Tb1.objects.filter(id__range=[1, 2]) # 范围bettwen and
ret=models.Book.objects.filter(price__gt=100)#大于
ret=models.Book.objects.filter(price__gte=99) # 大于等于 #ret=models.Book.objects.filter(publishDate__year=2017,publishDate__month=10)查询日期的
#ret=models.Book.objects.filter(author__startswith="张")#以什么开头 print(ret)
startswith,istartswith, endswith, iendswith
Django之ORM查询的更多相关文章
- Django之ORM查询复习与cookie
ORM查询总结: models.Book.objects.filter(**kwargs): querySet [obj1,obj2] models.Book.objects.filter(**kwa ...
- Django 的 orm 查询
一.模型关系表 1. 一对一 Author-AuthorDetail 关联字段可以在任意表下,但必须唯一约束.(unique约束) ad_id(unique约束) ad = models.oneToO ...
- [django]django的orm查询
实体 实体 出版社 category 作者 tag 书 文章 先学习一下基础的增删查改 django orm增删改查: https://www.cnblogs.com/iiiiiher/article ...
- Django之ORM查询进阶
基于双下划线的双表查询 分组与聚合函数 基于双下划线的双表查询 Django 还提供了一种直观而高效的方式在查询(lookups)中表示关联关系,它能自动确认 SQL JOIN 联系.要做跨关系查询, ...
- django优化--ORM查询
ORM提供了两个方法用来优化查询效率 1. select_related 有两张表:表结构如下: class Scheme(models.Model): """ 套餐类 ...
- Django之ORM查询操作详解
浏览目录 一般操作 ForeignKey操作 ManyToManyField 聚合查询 分组查询 F查询和Q查询 事务 Django终端打印SQL语句 在Python脚本中调用Django环境 其他操 ...
- Django 源码小剖: Django ORM 查询管理器
ORM 查询管理器 对于 ORM 定义: 对象关系映射, Object Relational Mapping, ORM, 是一种程序设计技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换.从 ...
- Django ORM 查询管理器
Django ORM 查询管理器 ORM 查询管理器 对于 ORM 定义: 对象关系映射, Object Relational Mapping, ORM, 是一种程序设计技术,用于实现面向对象编程语言 ...
- Django的ORM常用查询操作总结(Django编程-3)
Django的ORM常用查询操作总结(Django编程-3) 示例:一个Student model: class Student(models.Model): name=models.CharFiel ...
随机推荐
- mybatis教程之原理剖析
MyBatis是目前非常流行的ORM框架,功能很强大,然而其实现却比较简单.优雅.本文通过代理的方式来看下其实现 方式一:传统API方式 @Test public void add() throws ...
- HTML XML 介绍
一. HTML(HyperTextMark-upLanguage)即超文本标记语言,是WWW的描述语言. 二. XML即ExtentsibleMarkup Language(可扩展标记语言), XML ...
- [POI 2009]Lyz
Description 题库链接 初始时滑冰俱乐部有 \(1\) 到 \(n\) 号的溜冰鞋各 \(k\) 双.已知 \(x\) 号脚的人可以穿 \(x\) 到 \(x+d\) 的溜冰鞋.有 \(m\ ...
- 通过webservice(System.Data.OracleClient)调试oracle
环境:vs2008+webservice+net framework3.5+oracle10g 原因:在项目中运行web程序,默认是使用vs内置web服务器(develop server),而这个内置 ...
- MySQL中表名重命名
第一种办法:##修改表名, TO 或AS都可以,也以省略掉 ## ALTER TABLE 表名 RENAME [TO|AS] 新表名 ALTER TABLE user10 RENAME TO user ...
- Ocelot中文文档-Route
路由(Routing) Ocelot主要功能是接收即将发来的请求并转发它们至下游服务.与此同时,以另一个http请求的形式(在将来这可能是任何传输的机制) Ocelot将一个请求的路由描述为另一个路由 ...
- MySQL学习(二) 数据类型
MySQL支持多种列类型:数值类型.日期/时间类型和字符串(字符)类型. 数值类型 数值类型又分为整数型与小数型 整数型 下面的表显示了需要的每个整数类型的存储和范围 创建一张表 mysql> ...
- IDEA创建简单SSM项目使用传统Jar包
#IDEA SSM项目使用传统Jar包 创建项目 下一步,命名 下一步,创建完成 下一步,创建资源文件夹resources 页面概览 左侧目录树 演示如下 一些简单的说明 其中包之间的层次调用 ent ...
- Compiler showing 'pi' symbol on error
Question: I was testing some code on Coliru, and I got a strange output. I went down the code and co ...
- How do I close a single buffer (out of many) in Vim?
I open several files in Vim by, for example, running vim a/*.php which opens 23 files. I then make m ...