上篇带大家简单做了一下图书表的创建、简单的查看和删除,今天会先简单介绍添加和修改,因为添加和修改与删除一样都很简单,本篇会相对多介绍一点单表查询,大家都知道数据库中查询是最重要的一部分,毕竟无论是修改还是删除等很多操作都是建立在查数据的基础上。

本篇导航:

今天所有例子用的延续上篇的数据库,book表也是延续上篇,接着昨天的建表,删除等功能扩展其他功能,所以有所疑问的可以先看上篇随笔:

http://www.cnblogs.com/liluning/p/7729607.html

一、添加

1、添加表记录

1)方式一

book_obj = models.Book(nid=nid,title=title,author=author,publishDate=publishDate,price=price)
book_obj.save() # 将数据保存到数据库

2)方式二

#book_obj可以得到返回值
book_obj=models.Book.objects.create(title=title,author=author,publishDate=publishDate,price=price)

2、template模版

1)首页的添加按钮

<a href="/addBook/"><button class="btn btn-primary">添加书籍</button></a>

2)添加页面的提交表单

<form action="/add/" method="post">
{% csrf_token %}
<tr>
<td><input type="text" name="title"></td>
<td><input type="text" name="author"></td>
<td><input type="date" name="publishDate"></td>
<td><input type="text" name="price"></td>
<td>
<button class="btn btn-info">提交</button>
</td>
</tr>
</form>

{% csrf_token %}之前说过 安全机制 在post请求中使用

3、url 分发

url(r'^add/', views.addBook),

4、视图函数views

def addBook(request) :
if request.method == "POST" :
nid = request.POST.get("nid")
title = request.POST.get("title")
author = request.POST.get("author")
publishDate = request.POST.get("publishDate")
price = request.POST.get("price")
# book_obj = models.Book(title=title,author=author,publishDate=publishDate,price=price)
# book_obj.save() # 将数据保存到数据库
book_obj = models.Book.objects.create(title=title, author=author, publishDate=publishDate, price=price)
return redirect("/index/")
return render(request, "add.html")

先讲拿到表单提交的数据 然后添加到表

添加表用那一个方式都可以 推荐方式二


二、单表查询

1、查询相关API

一定区分object与querySet的区别

昨天已做介绍:
<1> all():
<2> filter(): <3> get():
返回与所给筛选条件相匹配的对象,返回结果有且只有一个,如果符合筛选条件的对象超过一个或者没有都会抛出错误。(慎用)
<4> exclude():
它包含了与所给筛选条件不匹配的对象
<5> values():
返回一个ValueQuerySet——一个特殊的QuerySet,运行后得到的并不是一系列model的实例化对象,而是一个可迭代的字典序列
<6> values_list():
它与values()非常相似,它返回的是一个元组序列,values返回的是一个字典序列
<7> order_by():
对查询结果排序
<8> reverse():
对查询结果反向排序
<9> distinct():
从返回结果中剔除重复纪录
<10> count():
返回数据库中匹配查询(QuerySet)的对象数量。
<11> first():
返回第一条记录
<12> last():
返回最后一条记录
<13> exists():
如果QuerySet包含数据,就返回True,否则返回False

例如: <2>filter(nid=nid,title=title) ','可以起到数据库and的作用两个条件关系为且,在括号里并不能实现‘或’的条件关系,后面的随笔会随后一一介绍。 

2、双下划线之单表查询

1 models.Tb1.objects.filter(id__lt=10, id__gt=1)    # 获取id大于1 且 小于10的值
#__lte,__gte 小于等于 大于等于
2 models.Tb1.objects.filter(id__in=[11, 22, 33]) # 获取id等于11、22、33的数据
3 models.Tb1.objects.exclude(id__in=[11, 22, 33]) # not in
4 models.Tb1.objects.filter(name__contains="ven") #模糊查询
5 models.Tb1.objects.filter(name__icontains="ven") # icontains大小写不敏感
6 models.Tb1.objects.filter(id__range=[1, 2]) # 范围bettwen and
7 startswith,istartswith, endswith, iendswith

3、通过logging可以查看翻译成的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',
},
}
} 

将上面代码粘贴到setting配置文件里,当你的操作与数据库相关时 会将我们的写的语句翻译成sql语句在服务端打印。

4、以下代码只为测试sql语句和单表查询示例

1)url 分发

url(r'^query/', views.query),

2)视图函数views

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")

以 first 方法为例

从此处可以看出我们虽然在操作数据库时没有写sql语句,但是django将我们写的语句翻译成了sql语句


三、修改

1、修改表记录

修改表记录和添加表记录同样都有两个方法,我们在视图函数views里看修改表记录的具体应用

nid = request.POST.get("nid")
title=request.POST.get("title")
author=request.POST.get("author")
publishDate=request.POST.get("publishDate")
price=request.POST.get("price") # 修改方式1:save(效率低)
# book_obj=models.Book.objects.filter(nid=id)[0]
# 修改书名示例:
# book_obj.title="py2"
# book_obj.save() # 修改方式2:(推荐)
models.Book.objects.filter(nid=nid).update(title=title,author=author,publishDate=publishDate,price=price)
return redirect("/index/")

2、url 分发

url(r'^edit/(\d+)', views.editBook),

3、template模版

1)主页修改按钮

<a href="/edit/{{ book_obj.nid }}"><button class="btn btn-info">编辑</button></a>

2)数据来源和添加表数据相同 由template模版的form表单提交 不同的是修改的表单内需要默认原来的数据

<form action="/edit/{{ edit_obj.nid }}" method="post">
{% csrf_token %}
<tr>
<td>{{ forloop.counter}}<input type="hidden" name="nid" value="{{ edit_obj.nid }}"></td>
<td><input type="text" name="title" value="{{ edit_obj.title }}"></td>
<td><input type="text" name="author" value="{{ edit_obj.author }}"></td>
<td><input type="date" name="publishDate" value="{{ edit_obj.publishDate|date:"Y-m-d" }}"></td>
<td><input type="text" name="price" value="{{ edit_obj.price }}"></td>
<td>
<a href="/del/{{ edit_obj.nid }}"><input type="button" class="btn btn-danger" value="删除"></a>
<button class="btn btn-success">保存</button>
</td>
</tr>
</form>

最新文章

  1. BZOJ 3083: 遥远的国度 [树链剖分 DFS序 LCA]
  2. SDWebImage使用及原理
  3. 用MSoffice里的绘图工具
  4. Yii源码阅读笔记(十五)
  5. 再说TCP神奇的40ms
  6. 话说C语言const用法
  7. 使用Spring Boot和Gradle创建AngularJS项目
  8. Unity 角色复活和重新开始游戏
  9. 工具使用 eclipse the user operation is waiting for Building Working to be completed。
  10. 安装VMware vSphere 的目的就是在一台物理服务器上安装很多很多的虚拟机
  11. Linux改动文件权限记录
  12. Spring源码情操陶冶-AbstractApplicationContext#initApplicationEventMulticaster
  13. JavaSE之Long 详解 Long的方法简介以及用法
  14. php函数形参传值与传引用
  15. WebSocket原理与实践(三)--解析数据帧
  16. Linux 压缩、解压命令使用
  17. 读书笔记《Spring Boot实战 —— Java EE 开发的颠覆者》
  18. 解决win8.1电脑无法安装手机驱动问题
  19. [控件] ChangeColorLabel
  20. QN-H618 遥控器复制再生仪(拷贝机)

热门文章

  1. 201521123045 《JAVA程序设计》第1周学习总结
  2. 手写Maven的archetype项目脚手架
  3. cocos2dx 播放gif
  4. GCD之死锁体会
  5. jmeter测试教程
  6. 使用jquery的方法和技巧
  7. java中集合的增删改操作及遍历总结
  8. httpd网页身份认证
  9. H264 NAL解析
  10. C#中的原子操作Interlocked,你真的了解吗?