1、项目初始化,参考python-Django页码翻页效果展示
2、启动项目,在pycharm中控制台样例输出查看:
如:
from movie.models import Movie
Movie.objects.all()
如图:
3、查看执行的sql,在控制台中编写如下sql:
from django.db import connection
print(connection.queries)
如图:
4、在上图中 发现没有输出sql,具体原因也没查到,于是又重新创建了一个项目,在试了一下,发现又没有问题了,如下:
from post.models import Post
Post.objects.all()
from django.db import connection
print(connection.queries)
print(connection.queries[-1]['sql'])
如图:
5、修改orm返回时的对象信息:
重写模型类中的一下__str__方法,如下:
def __str__(self):
return u'Post:title:%s,desc:%s' % (self.title,self.desc)
6、编写查看最后一条执行sql语句的方法:
在Console中编写:
from post.models import *
def showsql():
...: from django.db import connection
...: print(connection.queries[-1]['sql'])
Post.objects.get(id=1)
showsql()
如图所示:
7、对比get方法与filter方法的异同:
Post.objects.get(id=1)
Post.objects.filter(id=1)
8、查看第一个与最后一个sql的区别:
Post.objects.first()
Post.objects.last()
如图:
9、查看数量的sql与python切片:
Post.objects.count()
Post.objects.all()[0:1]
Post.objects.all()[0:2]
如图: