python-Django使用orm的方式进行单表查询操作

我爱海鲸 2021-05-15 21:44:00 python

简介单表查询操作,显示并查看sql,修改orm返回时的对象信息

1、项目初始化,参考python-Django页码翻页效果展示


2、启动项目,在pycharm中控制台样例输出查看:

如:

from movie.models import Movie

Movie.objects.all()

如图:

undefined


3、查看执行的sql,在控制台中编写如下sql:

from django.db import connection

print(connection.queries)

如图:

undefined


4、在上图中 发现没有输出sql,具体原因也没查到,于是又重新创建了一个项目,在试了一下,发现又没有问题了,如下:

from post.models import Post

Post.objects.all()

from django.db import connection

print(connection.queries)

print(connection.queries[-1]['sql'])

如图:

undefined

undefined

5、修改orm返回时的对象信息:

重写模型类中的一下__str__方法,如下:

   def __str__(self):

        return u'Post:title:%s,desc:%s' % (self.title,self.desc)

undefined

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

如图所示:

undefined

7、对比get方法与filter方法的异同:

Post.objects.get(id=1)

Post.objects.filter(id=1)

undefined

8、查看第一个与最后一个sql的区别:

Post.objects.first()

Post.objects.last()

如图:

undefined

9、查看数量的sql与python切片:

Post.objects.count()

Post.objects.all()[0:1]

Post.objects.all()[0:2]

如图:

undefined

你好:我的2025