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查询的更多相关文章

  1. Django之ORM查询复习与cookie

    ORM查询总结: models.Book.objects.filter(**kwargs): querySet [obj1,obj2] models.Book.objects.filter(**kwa ...

  2. Django 的 orm 查询

    一.模型关系表 1. 一对一 Author-AuthorDetail 关联字段可以在任意表下,但必须唯一约束.(unique约束) ad_id(unique约束) ad = models.oneToO ...

  3. [django]django的orm查询

    实体 实体 出版社 category 作者 tag 书 文章 先学习一下基础的增删查改 django orm增删改查: https://www.cnblogs.com/iiiiiher/article ...

  4. Django之ORM查询进阶

    基于双下划线的双表查询 分组与聚合函数 基于双下划线的双表查询 Django 还提供了一种直观而高效的方式在查询(lookups)中表示关联关系,它能自动确认 SQL JOIN 联系.要做跨关系查询, ...

  5. django优化--ORM查询

    ORM提供了两个方法用来优化查询效率 1. select_related 有两张表:表结构如下: class Scheme(models.Model): """ 套餐类 ...

  6. Django之ORM查询操作详解

    浏览目录 一般操作 ForeignKey操作 ManyToManyField 聚合查询 分组查询 F查询和Q查询 事务 Django终端打印SQL语句 在Python脚本中调用Django环境 其他操 ...

  7. Django 源码小剖: Django ORM 查询管理器

    ORM 查询管理器 对于 ORM 定义: 对象关系映射, Object Relational Mapping, ORM, 是一种程序设计技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换.从 ...

  8. Django ORM 查询管理器

    Django ORM 查询管理器 ORM 查询管理器 对于 ORM 定义: 对象关系映射, Object Relational Mapping, ORM, 是一种程序设计技术,用于实现面向对象编程语言 ...

  9. Django的ORM常用查询操作总结(Django编程-3)

    Django的ORM常用查询操作总结(Django编程-3) 示例:一个Student model: class Student(models.Model): name=models.CharFiel ...

随机推荐

  1. POJ 1860 Currency Exchange(如何Bellman-Ford算法判断图中是否存在正环)

    题目链接: https://cn.vjudge.net/problem/POJ-1860 Several currency exchange points are working in our cit ...

  2. C# QuartZ使用实例写成服务

    官方学习文档:http://www.quartz-scheduler.net/documentation/index.html 官方的源代码下载:http://sourceforge.net/proj ...

  3. 【转】Dubbo和JDK的SPI究竟有何区别?

    前言 上一篇简单的介绍了spi的基本一些概念,但是其实Dubbo对jdk的spi进行了一些改进,具体改进了什么,来看看文档的描述 JDK 标准的 SPI 会一次性实例化扩展点所有实现,如果有扩展实现初 ...

  4. Mongodb的基本语法

    前段时间工作上面由于没有多少事所以玩了玩mongodb,学习了它的基本语法,然后现在在这里做一个简单的总结. 1.我是在win平台上面,启动的话比较麻烦,所以我就简单的把启动过程做了个批处理文件 启动 ...

  5. Nginx 500错误总结

    Nginx 500错误总结 500(服务器内部错误) 服务器遇到错误,无法完成请求. 501(尚未实施) 服务器不具备完成请求的功能.例如,当服务器无法识别请求方法时,服务器可能会返回此代码. 502 ...

  6. 关于 ul 嵌套 li 并且再嵌套 a 的 BUG

    在写网页的过程中,总是写完了这一套,样式出了问题又去找问题废了好长时间总结一下写法以下是结构 经常会出现 li 里面与文字不在一个高度上 <div class="indicators& ...

  7. 洛谷P4424 [HNOI/AHOI2018]寻宝游戏(思维题)

    题意 题目链接 Sol 神仙题Orz Orz zbq爆搜70.. 考虑"与"和"或"的性质 \(0 \& 0 = 0, 1 \& 0 = 0\) ...

  8. npm 全局执行 update 、 outdated 出现 npm-debug.log 404 错误的问题

    想要执行一次全局更新,发现屡次报错: # npm update -g 提示的错误信息包含如下内容: npm ERR! code E404 npm ERR! 404 Registry returned ...

  9. 2018-01-11 Antlr4的分析错误处理

    中文编程知乎专栏原文地址 (前文通用型的中文编程语言探讨之一: 高考, 即使是这"第一步", 即使一切顺利达到列出的功能恐怕也需要个人数年的业余时间. 看到不少乎友都远更有资本和实 ...

  10. 消除2个按钮之间1px细节引起的冲突

    1.代码 <!doctype html> <html lang="en"> <head> <meta charset="UTF- ...