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>

<!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>

<!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