django模型系统二

常用查询及表关系的实现

1.常用查询

每一个django模型类,都有一个默认的管理器 objects

QuerySet表示数据库中对象的列表,它可以有0到多个过滤器。过滤器通过给定参数,缩小查询范围。

QuerySet等同于select语句,过滤器是一个限制子句,比如where,limit。

  all() 获取所有

Student.objects.all()    #返回的是queryset

  获取第一条

 Student.objects.first()  #返回的是对象

  获取最后一条

Student.objects.last()    #返回的是对象

  get(**kwargs)根据给定的条件获取一个对象,如果符合多个或没有就会报错

  filter(**kwargs)过滤,根据参数提供的条件,获取一个过滤器后的QuerySet,多个条件等同于select子句使用and连接,关键字的参数的形参必须是模型中的字段名。

  

Student.objects.filter(name='张三').filter(sex=0)

  exclude(**kwargs)用法和filter一样,作用相反,它是排除

  order(*fileds),根据给定的字段排序

res.order_by('-age','name')   #默认asc, -age代表反向排序

  切片:使用列表的切片语法操作query,除了不能用负索引,其他都可以,他等价于LIMIT与OFFSET子句

  values(*fileds)返回queryset,这个queryset返回的是一个字典列表,参数fields指定了select中我们想要限制查询的字段。返回的字典列表中,只会包含我们指定的字段。如果不指定,包含所有字段。

res=Student.objects.values('name')    

  only(*fileds)返回一个queryset,跟values一样,区别在于这个queryset是对象列表,only一定包含主键。

res=Student.objects.only('name')  

  defer(*fields)用法与only相反

res=Student.objects.defer('sex')  

  多条件OR连接,需要实现OR条件,我们要使用Q对象

from django.db.models import Q 
res=Student.objects.filter(Q(age=18)|Q(age=19)).only('name') 
等价于下面的sql:
SELECT `teacher_student`.`id`, `teacher_student`.`name` FROM `teacher_student` WHERE
(`teacher_student`.`age` = 18 OR `teacher_student`.`age` = 19)

  查询条件:

  exact  精确匹配    

 res=Student.objects.filter(name__exact='张三')  

  iexact  忽略大小写

res=Student.objects.filter(name__iexact='张三')  

  contains

res=Student.objects.filter(name__contains='张三')  

  icontains

  in

res=Student.objects.filter(name__in=[18,20])

  gt  (great than)

  gte  (great than equal)

res=Student.objects.filter(name__gte=18) 

  lt  (less than)

res=Student.objects.filter(name__lt=18)  

  lte

  startswith  以什么开始

res=Student.objects.filter(name__startswith='张')   

  istartswith

  endwith     以什么结尾

  iendwith

  range  范围区间

res=Student.objects.filter(name__range=(18,20)) 

  isnull

res=Student.objects.filter(name__isnull=True)   

语法都是field__condition 是两个下划线

count返回queryset的长度

聚合函数

Avg

#计算同学们的年龄平均值
res=Student.objects.aggregate(age_avg=Avg('age'))  

Max最大值

#找到年龄最大的学生
res=Student.objects.aggregate(age_max=Max('age'))  

Min最小值

sum求和

分组,聚合,分组需要结合values,annotate和聚合方法看下面的案例

#查询男生女生分别有多少人
from django.db.models import Count 

res=Student.objects.values('sex').annotate(Count('sex'))

2.常用模型字段类型

参考官方文档

https://docs.djangoproject.com/en/2.1/ref/models/fields/#field-types

 3.表关系实现

django中,模型通过特殊的字段进行关系连接。

一对一

一对多

多对多

猜你喜欢

转载自www.cnblogs.com/jonney-2019/p/10618924.html
今日推荐