Django 的ORM 数据操作

from teatcher.models import Student      导入app(teatcher)下的模型(Student) 

In [11]: res = Student.objects.all().query In [12]: print(res) SELECT `teatcher_student`.`id`, `teatcher_student`.`name`, `teatcher_student`.`sex`, `teatcher_student`.`age`, `teatcher_student`.`qq`, `teatcher_student`.`phone`, `teatcher_student`.`c_time`, `teatcher_student`.`m_time` FROM `teatcher_student` # Student.ojbects.all() 和select * from Student 效果一样. 返回是object

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

id = models.IntegerField(primary_key=True)   # 主键
mame = models.CharField(max_length=50,unique=True) # unqiue 唯一
num = models.CharField('班级编号203班,102班',max_length=20, unique=True) 备注,最大长度,唯一
qq = models.CharField(max_length=20, default='')  # 字符类型
phone = models.CharField(max_length=30,default='')
c_time = models.DateTimeField('创建时间', auto_now_add=True) # auto_now_add 只加一次
m_time = models.DateTimeField('修改时间', auto_now=True) # auto_now 每次修改 会更新

3.常用查询*****
通过模型类上的管理器来构造QuerySet。
- 模型类上的管理器是啥?
**模型类.objects:

如:     Student.objects    object 是 Student 实例的管理器


- QuerySet 表示数据库中对象的集合。
等同于select 语句。 惰性的
案例:

- first() 获取第一条 返回的是对象
- last() 获取最后一条 返回的也是一个对象

In [12]: Student.objects.first()                                                                                                                                                                                                                      
Out[12]: <Student: 啊呆-18>      #返回对象

In [13]: Student.objects.last()                                                                                                                                                                                                                       
Out[13]: <Student: 小红-21>

In [20]: res = Student.objects.last()

In [21]: print(res) 

小红-21

In [22]: res .qq
Out[22]: '28456'

In [23]: print(res)
小红-21

 


思考:排序规则? 默认通过主键。通过_meta 设置
- get(**kwargs) 根据给定的条件,获取一个对象,如果有多个对象符合,保存

Student.objects.get(id=1)    #get 和 主键配合,, get(pk=1) ,获取到多条结果时,会报错.
Out[29]: <Student: 啊呆-18>

- all() 获取所有记录 返回的是queryset

- filter(**kwargs) 根据给定的条件,获取一个过滤后的queryset,多个条件使用and连接。

In [32]: Student.objects.filter(age=18)                                                                                                                                 
Out[32]: <QuerySet [<Student: 啊呆-18>, <Student: 小张-18>, <Student: 小黄-18>, <Student: 小兰-18>]>

In [33]: Student.objects.filter(age=18,sex=1)       多个条件','分割                                                                                                                     
Out[33]: <QuerySet [<Student: 小张-18>, <Student: 小黄-18>, <Student: 小兰-18>]>

In [35]: res = Student.objects.filter(age=18,sex=1)   #返回 对象集

In [36]: res[0].name
Out[36]: '小张'

 


- exclude(**kwargs) 跟filter使用方法一致,作用想反,它是排除。

# exclude  不包含的意思.不包含 age=18,sex=1的
In [38]: res = Student.objects.exclude(age=18,sex=1)                                                                                                                      

In [39]: print(res)                                                                                                                                                     
<QuerySet [<Student: 啊呆-18>, <Student: 小绿-19>, <Student: 小红-21>]>

In [45]:print(res.query)   

In [45]:SELECT `teatcher_student`.`id`, `teatcher_student`.`name`, `teatcher_student`.`sex`, `teatcher_student`.`age`, `teatcher_student`.`qq`, `teatcher_student`.`phone`, `teatcher_student`.`c_time`, `teatcher_student`.`m_time` FROM `teatcher_student` WHERE NOT (`teatcher_student`.`age` = 18 AND `teatcher_student`.`sex` = 1)

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

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

Student.objects.filter(Q(age=0)|Q(age=18))'

<QuerySet [<Student: 啊呆-18>, <Student: 小张-18>, <Student: 小黄-18>, <Student: 小兰-18>]>

 

QuerySet[0].name 取值 ,<><表示是一个对象>

 

- values(*fields) 返回一个queryset,返回一个字典列表,而不是数据对象。

In [50]: Student.objects.values('name')                                                                                                                                 
Out[50]: <QuerySet [{'name': '啊呆'}, {'name': '小张'}, {'name': '小黄'}, {'name': '小兰'}, {'name': '小绿'}, {'name': '小红'}]>

In [54]: print(res.query)
SELECT `teatcher_student`.`name` FROM `teatcher_student`

 
  
In [51]: Student.objects.values('name','sex')                                                                                                                           
Out[51]: <QuerySet [{'name': '啊呆', 'sex': 0}, {'name': '小张', 'sex': 1}, {'name': '小黄', 'sex': 1}, {'name': '小兰', 'sex': 1}, {'name': '小绿', 'sex': 0}, {'name':x': 0}]>
 

 


- only(*fiels) 返回querySet ,对象列表,注意only一定包含主键字段

In [55]: res =Student.objects.only('name')                                                                                                                              

In [58]: print(res.query)                                                                                                                                               
SELECT `teatcher_student`.`id`, `teatcher_student`.`name` FROM `teatcher_student`

In [59]: print(res)                                                                                                                                                     
<QuerySet [<Student: 啊呆-18>, <Student: 小张-18>, <Student: 小黄-18>, <Student: 小兰-18>, <Student: 小绿-19>, <Student: 小红-21>]>

 


- defer(*fields) 返回一个QuerySet,作用和only相反   

不包含 *fidelfs  的记录

In [60]: res =Student.objects.defer('name')                                                                                                                             

In [61]: print(res.query)                                                                                                                                               
SELECT `teatcher_student`.`id`, `teatcher_student`.`sex`, `teatcher_student`.`age`, `teatcher_student`.`qq`, `teatcher_student`.`phone`, `teatcher_student`.`c_time`, `teatcher_student`.`m_time` FROM `teatcher_student`

In [62]: print(res)                                                                                                                                                     
<QuerySet [<Student: 啊呆-18>, <Student: 小张-18>, <Student: 小黄-18>, <Student: 小兰-18>, <Student: 小绿-19>, <Student: 小红-21>]>

 


- order_by(*fields) 根据给定的字段来排序 默认是顺序,字段名前加上 ‘-’代表反序
- 切片 和python的列表切片用法相似,不支持负索引,数据量大时不用步长
*** 切片过后,不再支持,附加过滤条件与排序

In [63]: res =Student.objects.defer('name').order_by('name')                                                                                                            

In [64]: print(res)                                                                                                                                                     
<QuerySet [<Student: 啊呆-18>, <Student: 小兰-18>, <Student: 小张-18>, <Student: 小红-21>, <Student: 小绿-19>, <Student: 小黄-18>]>

In [65]: print(res.query)                                                                                                                                               
SELECT `teatcher_student`.`id`, `teatcher_student`.`sex`, `teatcher_student`.`age`, `teatcher_student`.`qq`, `teatcher_student`.`phone`, `teatcher_student`.`c_time`, `teatcher_student`.`m_time` FROM `teatcher_student` ORDER BY `teatcher_student`.`name` ASC

 

查询结果 切片
In [9]: Student.objects.all() Out[9]: <QuerySet [<Student: 啊呆-18>, <Student: 小张-18>, <Student: 小黄-18>, <Student: 小兰-18>, <Student: 小绿-19>, <Student: 小红-21>]> In [10]: Student.objects.all()[2:4] # 查询返回结果中的第三到第四条 Out[10]: <QuerySet [<Student: 小黄-18>, <Student: 小兰-18>]>

print(Student.objects.all()[2:4].query)
SELECT `teatcher_student`.`id`, `teatcher_student`.`name`, `teatcher_student`.`sex`, `teatcher_student`.`age`, `teatcher_student`.`qq`, `teatcher_student`.`phone`, `teatcher_student`.`c_time`, `teatcher_student`.`m_time` FROM `teatcher_student` LIMIT 2 OFFSET 2

 


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

(字段名__exact=19)    等同   (字段=19)
 Student.objects.get(age__exact=19)                                                                                                                             
Out[15]: <Student: 小绿-19>

- iexact

In [21]: Student.objects.create(name='zhuoDa')   # 字段=xXXXx  i 表示 忽略大小写                                                                                                                       
Out[21]: <Student: zhuoDa-0>

In [22]: Student.objects.only('name').filter(name__iexact='zhuoda')                                                                                                     
Out[22]: <QuerySet [<Student: zhuoda-0>, <Student: Zhuoda-0>, <Student: ZhuoDa-0>, <Student: zhuoDa-0>]>

  

- contains
- icontains

- contains  # 包含    like  %xxx%
- icontains# 忽略大小写的 包含 like %xxx%
BINARY 关键字,区分大小写

In [25]: print(Student.objects.only('name').filter(name__contains='da').query)                                                                                          
SELECT `teatcher_student`.`id`, `teatcher_student`.`name` FROM `teatcher_student` WHERE `teatcher_student`.`name` LIKE BINARY %da%

In [26]: print(Student.objects.only('name').filter(name__icontains='da').query)                                                                                         
SELECT `teatcher_student`.`id`, `teatcher_student`.`name` FROM `teatcher_student` WHERE `teatcher_student`.`name` LIKE %da%

- in

In [34]: Student.objects.only('name').filter(name__in=['小张','小黄'])   #  (name__in=[1,2,3,4,5])                                                                                                 
Out[34]: <QuerySet [<Student: 小张-18>, <Student: 小黄-18>]>

 

- range

In [36]: Student.objects.only('name').filter(age__range=(5,50))           # range(小,大) 只能 从小 到大 写.                                                                                                
Out[36]: <QuerySet [<Student: 啊呆-18>, <Student: 小张-18>, <Student: 小黄-18>, <Student: 小兰-18>, <Student: 小绿-19>, <Student: 小红-21>]>

In [37]: print(Student.objects.only('name','age').filter(age__range=(5,50)).query)
SELECT `teatcher_student`.`id`, `teatcher_student`.`name`, `teatcher_student`.`age` FROM `teatcher_student` WHERE `teatcher_student`.`age` BETWEEN 5 AND 50

 


- gt
- gte
- lt
- lte

In [38]: print(Student.objects.only('name','age').filter(age__gt=5).query)                                                                                              
SELECT `teatcher_student`.`id`, `teatcher_student`.`name`, `teatcher_student`.`age` FROM `teatcher_student` WHERE `teatcher_student`.`age` > 5

 


- startswith    #  什么开头的
- istartswith  #  什么 开头 忽略大小写
- endswith  #  什么结尾的
- iendswith  #  什么 结尾 忽略大小写


In [39]: print(Student.objects.only('name','age').filter(name__startswith='z').query) SELECT `teatcher_student`.`id`, `teatcher_student`.`name`, `teatcher_student`.`age` FROM `teatcher_student` WHERE `teatcher_student`.`name` LIKE BINARY z% In [40]: print(Student.objects.only('name','age').filter(name__istartswith='z').query) SELECT `teatcher_student`.`id`, `teatcher_student`.`name`, `teatcher_student`.`age` FROM `teatcher_student` WHERE `teatcher_student`.`name` LIKE z%

  


- 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
- 分组,聚合
结合 Values,annotate 和聚合方法一起实现

In [42]: from django.db.models import Count,Avg,Max,Min,Sum
In [44]: Student.objects.aggregate(age_avg=Avg('age'))    #(临时字段名= Avg('字段'))                                                                                                               
Out[44]: {'age_avg': 11.2}

In [46]: Student.objects.aggregate(ages=Min('age'))                                                                                                                     
Out[46]: {'ages': 0}


In [47]: Student.objects.aggregate(ages=Max('age'))                                                                                                                     
Out[47]: {'ages': 21}

In [48]: Student.objects.aggregate(ages=Count('age'))                                                                                                                   
Out[48]: {'ages': 10}

 


查询男生有几个,女生有几个

In [49]: Student.objects.values('sex').annotate(num=Count('sex'))                                                                                                       
Out[49]: <QuerySet [{'sex': 0, 'num': 7}, {'sex': 1, 'num': 3}]>

In [50]: print(Student.objects.values('sex').annotate(num=Count('sex')).query)                                                                                          
SELECT `teatcher_student`.`sex`, COUNT(`teatcher_student`.`sex`) AS `num` FROM `teatcher_student` GROUP BY `teatcher_student`.`sex` ORDER BY NULL

 ****按字段的小写 排序

关键字:Lower  

In [6]: from django.db.models.functions import Lower                                                                                                              

In [7]: student.objects.all()                                                                                                                                     
Out[7]:^[[A^[[A<QuerySet [<student: 第一条-18>, <student: 第二条-18>, <student: 第三条-22>, <student: 第四条-18>]>

In [8]: student.objects.order_by(Lower('name'))                                                                                                                   
Out[8]: <QuerySet [<student: 第一条-18>, <student: 第三条-22>, <student: 第二条-18>, <student: 第四条-18>]>

In [9]: print(student.objects.order_by(Lower('name')).query)                                                                                                      
SELECT `student_student`.`id`, `student_student`.`name`, `student_student`.`sex`, `student_student`.`age`, `student_student`.`qq`, `student_student`.`phone`, `student_student`.`c_time` FROM `student_student` ORDER BY LOWER(`student_student`.`name`) ASC

 

非数值类型的倒序

In [12]: student.objects.order_by(Lower('name').desc())                                                                                                           
Out[12]: <QuerySet [<student: 第四条-18>, <student: 第二条-18>, <student: 第三条-22>, <student: 第一条-18>]>

In [13]: print(student.objects.order_by(Lower('name').desc()).query)
SELECT `student_student`.`id`, `student_student`.`name`, `student_student`.`sex`, `student_student`.`age`, `student_student`.`qq`, `student_student`.`phone`, `student_student`.`c_time` FROM `student_student` ORDER BY LOWER(`student_student`.`name`) DESC

 


4.表关系实现

 

转载于:https://www.cnblogs.com/crave/p/10435977.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值