Django 的ORM 数据操作

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


- 常用查询条件 filter,exclude, get
- exact
- iexact
- contains
- icontains
- in
- range
- gt
- gte
- lt
- lte
- 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
- 分组,聚合
结合 Values,annotate 和聚合方法一起实现
查询男生有几个,女生有几个
4.表关系实现

猜你喜欢

转载自www.cnblogs.com/crave/p/10435977.html