django 第六课 模型第二讲

1.常用的字段类型
  官方文档地址
  https://docs.djangoproject.com/en/2.1/ref/models/fields/#field-types

2.字段的常用参数
  https://docs.djangoproject.com/en/2.1/ref/models/fields/#field-options

3.常用查询

  通过模型类上的管理器来构造QuerySet
  模型类上的管理是啥?
  模型类型.objects

QuerySet 表示数据库种对象的集合,等同于Select 语句 惰性的

案例:

-all() 获取所有记录,返回都是QuerySet

In [17]: Student.objects.all()
Out[17]: <QuerySet [<Student: xinlan-0>, <Student: donghao-0>, <Student: liuyifei-0>, <Student: liutao-0>, <Student: liudehua-0>, <Student: zhangtianbao-0>]>

first() 获取第一条 返回的是对象

last() 获取最后一条返回的对象

In [19]: s = Student.objects.first()                                                                       

In [20]: s
Out[20]: <Student: xinlan-0>

In [21]: s = Student.objects.last()                                                                        

In [22]: s
Out[22]: <Student: zhangtianbao-0>

get(**kwargs) 根据给定的条件获取一个对象

 

In [25]: s = Student.objects.get(sex = 0)
---------------------------------------------------------------------------
DoesNotExist                              Traceback (most recent call last)
<ipython-input-25-68f9926d8462> in <module>
----> 1 s = Student.objects.get(sex = 0)

~/.virtualenvs/django/lib/python3.6/site-packages/django/db/models/manager.py in manager_method(self, *args, **kwargs)
     80         def create_method(name, method):
     81             def manager_method(self, *args, **kwargs):
---> 82                 return getattr(self.get_queryset(), name)(*args, **kwargs)
     83             manager_method.__name__ = method.__name__
     84             manager_method.__doc__ = method.__doc__

~/.virtualenvs/django/lib/python3.6/site-packages/django/db/models/query.py in get(self, *args, **kwargs)
    397             raise self.model.DoesNotExist(
    398                 "%s matching query does not exist." %
--> 399                 self.model._meta.object_name
    400             )
    401         raise self.model.MultipleObjectsReturned(

DoesNotExist: Student matching query does not exist.

- filter(**kwargs) 根据给定的条件,获取一个过滤后的queryset,多个条件使用and连接。
- exclude(**kwargs) 跟filter使用方法一致,作用想反,它是排除。

In [32]: res =Student.objects.filter(age=0,sex=1)                                                          

In [33]: print(res.query)
SELECT `teacher_student`.`id`, `teacher_student`.`name`, `teacher_student`.`age`, `teacher_student`.`sex`, `teacher_student`.`qq`, `teacher_student`.`phone`, `teacher_student`.`c_time` FROM `teacher_student` WHERE (`teacher_student`.`age` = 0 AND `teacher_student`.`sex` = 1)

In [34]: res =Student.objects.exclude(age=0,sex=1)                                                         

In [35]: print(res.query)
SELECT `teacher_student`.`id`, `teacher_student`.`name`, `teacher_student`.`age`, `teacher_student`.`sex`, `teacher_student`.`qq`, `teacher_student`.`phone`, `teacher_student`.`c_time` FROM `teacher_student` WHERE NOT (`teacher_student`.`age` = 0 AND `teacher_student`.`sex` = 1)

- 多条件的OR连接 用到Q对象,django.db.models.Q

In [36]: from django.db.models import Q                                                                    

In [37]: res = Student.objects.filter(Q(age=0)|Q(age=1))                                                   

In [38]: print(res.query)
SELECT `teacher_student`.`id`, `teacher_student`.`name`, `teacher_student`.`age`, `teacher_student`.`sex`, `teacher_student`.`qq`, `teacher_student`.`phone`, `teacher_student`.`c_time` FROM `teacher_student` WHERE (`teacher_student`.`age` = 0 OR `teacher_student`.`age` = 1)

- values(*fields) 返回一个queryset,返回一个字典列表,而不是数据对象。
- only(*fiels) 返回querySet ,对象列表,注意only一定包含主键字段
- defer(*fields) 返回一个QuerySet,作用和only相反

In [39]: res = Student.objects.values(‘name‘)                                                              

In [40]: print(res)
<QuerySet [{‘name‘: ‘xinlan‘}, {‘name‘: ‘donghao‘}, {‘name‘: ‘liuyifei‘}, {‘name‘: ‘liutao‘}, {‘name‘: ‘liudehua‘}, {‘name‘: ‘zhangtianbao‘}]>

In [41]: res
Out[41]: <QuerySet [{‘name‘: ‘xinlan‘}, {‘name‘: ‘donghao‘}, {‘name‘: ‘liuyifei‘}, {‘name‘: ‘liutao‘}, {‘name‘: ‘liudehua‘}, {‘name‘: ‘zhangtianbao‘}]>

In [42]: res[0][‘name‘]
Out[42]: ‘xinlan‘

In [43]: res = Student.objects.values(‘name‘,‘age‘).filter(age=0)                                          

In [44]: print(res.query)
SELECT `teacher_student`.`name`, `teacher_student`.`age` FROM `teacher_student` WHERE `teacher_student`.`age` = 0

In [45]: res = Student.objects.only(‘name‘,‘age‘).filter(age=0)                                            

In [46]: print(res.query)
SELECT `teacher_student`.`id`, `teacher_student`.`name`, `teacher_student`.`age` FROM `teacher_student` WHERE `teacher_student`.`age` = 0

In [47]: res[0]
Out[47]: <Student: xinlan-0>

In [48]: res[0].c_time
Out[48]: datetime.datetime(2019, 2, 25, 14, 55, 14, 24220, tzinfo=<UTC>)

In [49]: res = Student.objects.defer(‘name‘,‘age‘)                                                         

In [50]: print(res.query)
SELECT `teacher_student`.`id`, `teacher_student`.`sex`, `teacher_student`.`qq`, `teacher_student`.`phone`, `teacher_student`.`c_time` FROM `teacher_student`

order_by(*fields) 根据给定的字段来排序 默认是顺序,字段名前加上 ‘-’代表反序

 1 In [51]: res = Student.objects.order_by(‘c_time‘)
 2
 3 In [52]: res = Student.objects.order_by(‘c_time‘).only(‘name‘)
 4
 5 In [53]: print(res.query)
 6 SELECT `teacher_student`.`id`, `teacher_student`.`name` FROM `teacher_student` ORDER BY `teacher_student`.`c_time` ASC
 7
 8 In [54]: res = Student.objects.order_by(‘-c_time‘).only(‘name‘)
 9
10 In [55]: print(res.query)
11 SELECT `teacher_student`.`id`, `teacher_student`.`name` FROM `teacher_student` ORDER BY `teacher_student`.`c_time` DESC

- 切片 和python的列表切片用法相似,不支持负索引,数据量大时不用步长
*** 切片过后,不再支持,附加过滤条件与排序

In [56]: res = Student.objects.all()[:5]                                                                   

In [57]: print(res.query)
SELECT `teacher_student`.`id`, `teacher_student`.`name`, `teacher_student`.`age`, `teacher_student`.`sex`, `teacher_student`.`qq`, `teacher_student`.`phone`, `teacher_student`.`c_time` FROM `teacher_student`  LIMIT 5

In [58]: res = Student.objects.all()[2:4]                                                                  

In [59]: print(res.query)
SELECT `teacher_student`.`id`, `teacher_student`.`name`, `teacher_student`.`age`, `teacher_student`.`sex`, `teacher_student`.`qq`, `teacher_student`.`phone`, `teacher_student`.`c_time` FROM `teacher_student`  LIMIT 2 OFFSET 2

- 常用查询条件 filter,exclude, get
- exact
- iexact

In [65]: Student.objects.get(id__exact=10)
Out[65]: <Student: liudehua-0>

In [66]: Student.objects.filter(id__exact=10)
Out[66]: <QuerySet [<Student: liudehua-0>]>

In [67]: print(res.query)
SELECT `teacher_student`.`id`, `teacher_student`.`name`, `teacher_student`.`age`, `teacher_student`.`sex`, `teacher_student`.`qq`, `teacher_student`.`phone`, `teacher_student`.`c_time` FROM `teacher_student`  LIMIT 2 OFFSET 2

In [68]: Student.objects.filter(id__iexact=10)
Out[68]: <QuerySet [<Student: liudehua-0>]>

In [69]: print(res.query)
SELECT `teacher_student`.`id`, `teacher_student`.`name`, `teacher_student`.`age`, `teacher_student`.`sex`, `teacher_student`.`qq`, `teacher_student`.`phone`, `teacher_student`.`c_time` FROM `teacher_student`  LIMIT 2 OFFSET 2

- contains
- icontains

In [72]: res = Student.objects.filter(name__contains=‘xinlan‘)                                             

In [73]: print(res.query)
SELECT `teacher_student`.`id`, `teacher_student`.`name`, `teacher_student`.`age`, `teacher_student`.`sex`, `teacher_student`.`qq`, `teacher_student`.`phone`, `teacher_student`.`c_time` FROM `teacher_student` WHERE `teacher_student`.`name` LIKE BINARY %xinlan%

In [74]: res = Student.objects.filter(name__icontains=‘xinlan‘)                                            

In [75]: print(res.query)
SELECT `teacher_student`.`id`, `teacher_student`.`name`, `teacher_student`.`age`, `teacher_student`.`sex`, `teacher_student`.`qq`, `teacher_student`.`phone`, `teacher_student`.`c_time` FROM `teacher_student` WHERE `teacher_student`.`name` LIKE %xinlan%

- in

In [76]: res =Student.objects.filter(name__in=[‘xinlan‘,‘donghao‘,‘asd‘])                                  

In [77]: print(res.query)
SELECT `teacher_student`.`id`, `teacher_student`.`name`, `teacher_student`.`age`, `teacher_student`.`sex`, `teacher_student`.`qq`, `teacher_student`.`phone`, `teacher_student`.`c_time` FROM `teacher_student` WHERE `teacher_student`.`name` IN (xinlan, donghao, asd)

- range

In [90]: res = Student.objects.filter(age__range=(0,4))                                                    

In [91]: print(res.query)
SELECT `teacher_student`.`id`, `teacher_student`.`name`, `teacher_student`.`age`, `teacher_student`.`sex`, `teacher_student`.`qq`, `teacher_student`.`phone`, `teacher_student`.`c_time` FROM `teacher_student` WHERE `teacher_student`.`age` BETWEEN 0 AND 4

- gt
- gte
- lt
- lte

In [93]: Student.objects.filter(age__gt=18)
Out[93]: <QuerySet []>

In [94]: print(res.query)
SELECT `teacher_student`.`id`, `teacher_student`.`name`, `teacher_student`.`age`, `teacher_student`.`sex`, `teacher_student`.`qq`, `teacher_student`.`phone`, `teacher_student`.`c_time` FROM `teacher_student` WHERE `teacher_student`.`age` BETWEEN 0 AND 4

In [95]: Student.objects.filter(age__gte=18)
Out[95]: <QuerySet []>

In [96]: print(res.query)
SELECT `teacher_student`.`id`, `teacher_student`.`name`, `teacher_student`.`age`, `teacher_student`.`sex`, `teacher_student`.`qq`, `teacher_student`.`phone`, `teacher_student`.`c_time` FROM `teacher_student` WHERE `teacher_student`.`age` BETWEEN 0 AND 4

In [97]: Student.objects.filter(age__lt=18)
Out[97]: <QuerySet [<Student: xinlan-0>, <Student: donghao-0>, <Student: liuyifei-0>, <Student: liutao-0>, <Student: liudehua-0>, <Student: zhangtianbao-0>]>

In [98]: Student.objects.filter(age__lte=18)
Out[98]: <QuerySet [<Student: xinlan-0>, <Student: donghao-0>, <Student: liuyifei-0>, <Student: liutao-0>, <Student: liudehua-0>, <Student: zhangtianbao-0>]>

- startswith
- istartswith
- endswith
- iendswith
- isnull True False 对应 IS NULL IS NOT NULL

 

- 聚合
from django.db.models import Count, Avg, Max, Min, Sum
通过queryset的aggregate方法
Student.objects.aggregate(age_avg=Avg(‘age‘)) # 计算平均年龄
- count
- 平均值 Avg

In [101]: from django.db.models import Avg,Max,Min,Sum                                                     

In [102]: Student.objects.aggregate(age__avg=Avg(‘age‘))
Out[102]: {‘age__avg‘: 0.0}

In [103]: Student.objects.all().count()
Out[103]: 6

In [104]: Student.objects.filter(name__startswith=‘xin‘).count()
Out[104]: 1

In [105]: Student.objects.aggregate(agg__max=Max(‘age‘))
Out[105]: {‘agg__max‘: 0}

In [106]: Student.objects.aggregate(agg__min=Mix(‘age‘))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-106-ade266492921> in <module>
----> 1 Student.objects.aggregate(agg__min=Mix(‘age‘))

NameError: name ‘Mix‘ is not defined

In [107]: Student.objects.aggregate(agg__min=Min(‘age‘))
Out[107]: {‘agg__min‘: 0}

In [108]: Student.objects.aggregate(agg__sum=Sum(‘age‘))
Out[108]: {‘agg__sum‘: 0}

- 分组,聚合
结合 Values,annotate 和聚合方法一起实现
查询男生有几个,女生有几个

In [109]: from django.db.models import Count                                                               

In [110]: Student.objects.values(‘sex‘).annotate(num=Count(‘sex‘))
Out[110]: <QuerySet [{‘sex‘: 1, ‘num‘: 6}]>

In [111]: res = Student.objects.values(‘sex‘).annotate(Count(‘sex‘))                                       

In [112]: print(res.query)
SELECT `teacher_student`.`sex`, COUNT(`teacher_student`.`sex`) AS `sex__count` FROM `teacher_student` GROUP BY `teacher_student`.`sex` ORDER BY NULL

原文地址:https://www.cnblogs.com/donghao1121/p/10434700.html

时间: 2024-10-11 22:41:56

django 第六课 模型第二讲的相关文章

django第六课 模型第一讲

1.数据库连接配置: django 连接mysql的配置流程: - 安装 pymysql pip install pymysql - 创建数据库用户 有创建数据库权限的用户 - 创建数据库 create database crm - 修改配置 settins 1 DATABASES = { 2 'default': { 3 'ENGINE': 'django.db.backends.mysql', 4 'NAME': 'crm', 5 'USER':'root', 6 'PASSWORD':''

Django框架(六):模型(二) 字段查询、查询集

1. 字段查询 通过模型类.objects属性可以调用如下函数,实现对模型类对应的数据表的查询. 函数名 功能 返回值 说明 get 返回表中满足条件的一条且只能有一条数据. 返回值是一个模型类对象. 参数中写查询条件. 1)如果查到多条数据,则抛异常MultipleObjectsReturned. 2)查询不到数据,则抛异常:DoesNotExist. all 返回模型类对应表格中的所有数据. 返回值是QuerySet类型 查询集 filter 返回满足条件的数据. 返回值是QuerySet类

Django 第六课 【模板继承】

在前端页面开发中,有些代码是需要重复使用的.这种情况可以使用 'include' 标签来实现.也可以使用另外一个比较强大的方式来实现,那就是模板继承.模板继承类似于 'python' 中的类,在父类中可以先定义好一些变量和方法,然后在子类中实现,模板继承也可以在父模板中先定义好一些子模板需要用到的代码.然后子模板直接继承就可以了,并且因为子模板肯定有自己不同的代码,因此可以在父模板中定义一个block接口,然后在子模板再去实现,以下是父模板的代码: {% load static %} <! DO

16位汇编第六讲汇编指令详解第二讲

16位汇编第六讲汇编指令详解第二讲 1.比较指令 CMP指令 1.CMP指令是将目的操作数减去源操作数,按照定义相应的设置状态标志 2.CMP指令执行的功能与SUB指令(相减指令)一样,但是不同的是CMP指令之根据结果设置标志位 而不修改值 可以操作的指令格式 CMP reg,imm/reg/mem CMP mem,imm/reg 上面是CMP指令的语法,具体的也可以查询帮助文档,inter手册 inter手册查的办法 第一个框代表了CMP指令的所有语法 比如 reg,reg 表示可以比较寄存器

【Linux探索之旅】第二部分第六课:Nano,初学者的文本编辑器

内容简介 1.第二部分第六课:Nano,初学者的文本编辑器 2.第二部分第七课预告:软件安装,如虎添翼 Nano,初学者的文本编辑器 这一课比较简单,没有什么太难的概念.不过这一课会讲如何配置终端噢. 大家可以泡个泡面,烤只烤鸡:剥个卤蛋,慢慢来看. 之前的课程中,我们已经学会了在终端中用多种不同的方式来查看文件的内容,但是我们还不知道如何在终端中修改文件的内容. 为什么我们把文本编辑器推迟到现在来说呢?因为这是终端可以提供的强大功能之一. 在Linux终端的文本编辑器当中,比较著名的有:Nan

【C语言探索之旅】 第二部分第六课:创建你自己的变量类型

0 内容简介 1.课程大纲 2.第二部分第六课: 创建你自己的变量类型 3.第二部分第七课预告: 文件读写 课程大纲 我们的课程分为四大部分,每一个部分结束后都会有练习题,并会公布答案.还会带大家用C语言编写三个游戏. C语言编程基础知识 什么是编程? 工欲善其事,必先利其器 你的第一个程序 变量的世界 运算那点事 条件表达式 循环语句 实战:第一个C语言小游戏 函数 练习题 习作:完善第一个C语言小游戏 C语言高级技术 模块化编程 进击的指针,C语言王牌 数组 字符串 预处理 创建你自己的变量

libgdx3D第二讲-加载模型

定义: 将一个类(Adaptee)的接口转换成客户(Client)希望的另外一个接口(Target). 目标接口(Target):客户所期待的接口.目标可以是具体的或抽象的类,也可以是接口. 需要适配的类(Adaptee):需要适配的类或适配者类. 适配器(Adapter):使得一个东西适合另一个东西的东西.百度中定义为:接口转换器.通过包装一个需要适配的对象,把源接口转换成目标接口. 为什么要适配:需要的东西已做好,但是不能用,短时间又不能改造,想办法适配它. 作用: 使得原本由于接口不兼容而

第二课:第一讲Linux操作系统及常用命令

第二课:第一讲Linux操作系统及常用命令1.liunx中"X"表示图像显示协议X-window有三种:Gnome,KDE,Xface2.windows->.dll(dynamic link library)liunx->.so (shared object)3.认证:authentication授权:authorization审计:audition(通过日志记录下来实现审计机制)4.登录成功后的"[[email protected] root]"是pr

第二讲:第二课Linux操作系统及常用命令

第二讲:第二课Linux操作系统及常用命令1.date-显示系统时间修改时间2.liunx记时模式:晶体振荡器,高级的每万年误差一秒.主机上就是晶体振荡器纪时的.晶体振荡器要供电才行,主板上有纽扣电池.主板上的时间叫RTC,real time clockntp(network time protocl):网络时间协议linux:系统启动时读取RTC(硬件时钟 ),读取成功后不在使用RTC时间,系统内核自身通过软件方式模拟振荡器在系统内部模拟时间,建立系统时钟.date 显示系统时间clock 显