《Django model update的各种用法介绍》文章介绍了Django model的各种update操作,这篇文章就是她的姊妹篇,详细介绍Django model select的用法,配以对应MySQL的查询语句,理解起来更轻松。

基本操作

  1. # 获取所有数据,对应SQL:select * from User
  2. User.objects.all()
  3. # 匹配,对应SQL:select * from User where name = '运维咖啡吧'
  4. User.objects.filter(name='运维咖啡吧')
  5. # 不匹配,对应SQL:select * from User where name != '运维咖啡吧'
  6. User.objects.exclude(name='运维咖啡吧')
  7. # 获取单条数据(有且仅有一条,id唯一),对应SQL:select * from User where id = 724
  8. User.objects.get(id=123)

常用操作

  1. # 获取总数,对应SQL:select count(1) from User
  2. User.objects.count()
  3. # 获取总数,对应SQL:select count(1) from User where name = '运维咖啡吧'
  4. User.objects.filter(name='运维咖啡吧').count()
  5. # 大于,>,对应SQL:select * from User where id > 724
  6. User.objects.filter(id__gt=724)
  7. # 大于等于,>=,对应SQL:select * from User where id >= 724
  8. User.objects.filter(id__gte=724)
  9. # 小于,<,对应SQL:select * from User where id < 724
  10. User.objects.filter(id__lt=724)
  11. # 小于等于,<=,对应SQL:select * from User where id <= 724
  12. User.objects.filter(id__lte=724)
  13. # 同时大于和小于, 1 < id < 10,对应SQL:select * from User where id > 1 and id < 10
  14. User.objects.filter(id__gt=1, id__lt=10)
  15. # 包含,in,对应SQL:select * from User where id in (11,22,33)
  16. User.objects.filter(id__in=[11, 22, 33])
  17. # 不包含,not in,对应SQL:select * from User where id not in (11,22,33)
  18. User.objects.exclude(id__in=[11, 22, 33])
  19. # 为空:isnull=True,对应SQL:select * from User where pub_date is null
  20. User.objects.filter(pub_date__isnull=True)
  21. # 不为空:isnull=False,对应SQL:select * from User where pub_date is not null
  22. User.objects.filter(pub_date__isnull=False)
  23. # 匹配,like,大小写敏感,对应SQL:select * from User where name like '%sre%',SQL中大小写不敏感
  24. User.objects.filter(name__contains="sre")
  25. # 匹配,like,大小写不敏感,对应SQL:select * from User where name like '%sre%',SQL中大小写不敏感
  26. User.objects.filter(name__icontains="sre")
  27. # 不匹配,大小写敏感,对应SQL:select * from User where name not like '%sre%',SQL中大小写不敏感
  28. User.objects.exclude(name__contains="sre")
  29. # 不匹配,大小写不敏感,对应SQL:select * from User where name not like '%sre%',SQL中大小写不敏感
  30. User.objects.exclude(name__icontains="sre")
  31. # 范围,between and,对应SQL:select * from User where id between 3 and 8
  32. User.objects.filter(id__range=[3, 8])
  33. # 以什么开头,大小写敏感,对应SQL:select * from User where name like 'sh%',SQL中大小写不敏感
  34. User.objects.filter(name__startswith='sre')
  35. # 以什么开头,大小写不敏感,对应SQL:select * from User where name like 'sh%',SQL中大小写不敏感
  36. User.objects.filter(name__istartswith='sre')
  37. # 以什么结尾,大小写敏感,对应SQL:select * from User where name like '%sre',SQL中大小写不敏感
  38. User.objects.filter(name__endswith='sre')
  39. # 以什么结尾,大小写不敏感,对应SQL:select * from User where name like '%sre',SQL中大小写不敏感
  40. User.objects.filter(name__iendswith='sre')
  41. # 排序,order by,正序,对应SQL:select * from User where name = '运维咖啡吧' order by id
  42. User.objects.filter(name='运维咖啡吧').order_by('id')
  43. # 多级排序,order by,先按name进行正序排列,如果name一致则再按照id倒叙排列
  44. User.objects.filter(name='运维咖啡吧').order_by('name','-id')
  45. # 排序,order by,倒序,对应SQL:select * from User where name = '运维咖啡吧' order by id desc
  46. User.objects.filter(name='运维咖啡吧').order_by('-id')

进阶操作

  1. # limit,对应SQL:select * from User limit 3;
  2. User.objects.all()[:3]
  3. # limit,取第三条以后的数据,没有对应的SQL,类似的如:select * from User limit 3,10000000,从第3条开始取数据,取10000000条(10000000大于表中数据条数)
  4. User.objects.all()[3:]
  5. # offset,取出结果的第10-20条数据(不包含10,包含20),也没有对应SQL,参考上边的SQL写法
  6. User.objects.all()[10:20]
  7. # 分组,group by,对应SQL:select username,count(1) from User group by username;
  8. from django.db.models import Count
  9. User.objects.values_list('username').annotate(Count('id'))
  10. # 去重distinct,对应SQL:select distinct(username) from User
  11. User.objects.values('username').distinct().count()
  12. # filter多列、查询多列,对应SQL:select username,fullname from accounts_user
  13. User.objects.values_list('username', 'fullname')
  14. # filter单列、查询单列,正常values_list给出的结果是个列表,里边里边的每条数据对应一个元组,当只查询一列时,可以使用flat标签去掉元组,将每条数据的结果以字符串的形式存储在列表中,从而避免解析元组的麻烦
  15. User.objects.values_list('username', flat=True)
  16. # int字段取最大值、最小值、综合、平均数
  17. from django.db.models import Sum,Count,Max,Min,Avg
  18. User.objects.aggregate(Count(‘id’))
  19. User.objects.aggregate(Sum(‘age’))

时间字段

  1. # 匹配日期,date
  2. User.objects.filter(create_time__date=datetime.date(2018, 8, 1))
  3. User.objects.filter(create_time__date__gt=datetime.date(2018, 8, 2))
  4. # 匹配年,year
  5. User.objects.filter(create_time__year=2018)
  6. User.objects.filter(create_time__year__gte=2018)
  7. # 匹配月,month
  8. User.objects.filter(create_time__month__gt=7)
  9. User.objects.filter(create_time__month__gte=7)
  10. # 匹配日,day
  11. User.objects.filter(create_time__day=8)
  12. User.objects.filter(create_time__day__gte=8)
  13. # 匹配周,week_day
  14. User.objects.filter(create_time__week_day=2)
  15. User.objects.filter(create_time__week_day__gte=2)
  16. # 匹配时,hour
  17. User.objects.filter(create_time__hour=9)
  18. User.objects.filter(create_time__hour__gte=9)
  19. # 匹配分,minute
  20. User.objects.filter(create_time__minute=15)
  21. User.objects.filter(create_time__minute_gt=15)
  22. # 匹配秒,second
  23. User.objects.filter(create_time__second=15)
  24. User.objects.filter(create_time__second__gte=15)
  25. # 按天统计归档
  26. today = datetime.date.today()
  27. select = {'day': connection.ops.date_trunc_sql('day', 'create_time')}
  28. deploy_date_count = Task.objects.filter(
  29. create_time__range=(today - datetime.timedelta(days=7), today)
  30. ).extra(select=select).values('day').annotate(number=Count('id'))

Q 的使用

Q对象可以对关键字参数进行封装,从而更好的应用多个查询,可以组合&(and)、|(or)、~(not)操作符。

例如下边的语句

  1. from django.db.models import Q
  2. User.objects.filter(
  3. Q(role__startswith='sre_'),
  4. Q(name='公众号') | Q(name='运维咖啡吧')
  5. )

转换成SQL语句如下:

  1. select * from User where role like 'sre_%' and (name='公众号' or name='运维咖啡吧')

通常更多的时候我们用Q来做搜索逻辑,比如前台搜索框输入一个字符,后台去数据库中检索标题或内容中是否包含

  1. _s = request.GET.get('search')
  2. _t = Blog.objects.all()
  3. if _s:
  4. _t = _t.filter(
  5. Q(title__icontains=_s) |
  6. Q(content__icontains=_s)
  7. )
  8. return _t

外键:ForeignKey

表结构:

  1. class Role(models.Model):
  2. name = models.CharField(max_length=16, unique=True)
  3. class User(models.Model):
  4. username = models.EmailField(max_length=255, unique=True)
  5. role = models.ForeignKey(Role, on_delete=models.CASCADE)

正向查询:

  1. # 查询用户的角色名
  2. _t = User.objects.get(username='运维咖啡吧')
  3. _t.role.name

反向查询:

  1. # 查询角色下包含的所有用户
  2. _t = Role.objects.get(name='Role03')
  3. _t.user_set.all()

另一种反向查询的方法:

  1. _t = Role.objects.get(name='Role03')
  2. # 这种方法比上一种_set的方法查询速度要快
  3. User.objects.filter(role=_t)

第三种反向查询的方法:

如果外键字段有related_name属性,例如models如下:

  1. class User(models.Model):
  2. username = models.EmailField(max_length=255, unique=True)
  3. role = models.ForeignKey(Role, on_delete=models.CASCADE,related_name='roleUsers')

那么可以直接用related_name属性取到某角色的所有用户

  1. _t = Role.objects.get(name = 'Role03')
  2. _t.roleUsers.all()

M2M:ManyToManyField

表结构:

  1. class Group(models.Model):
  2. name = models.CharField(max_length=16, unique=True)
  3. class User(models.Model):
  4. username = models.CharField(max_length=255, unique=True)
  5. groups = models.ManyToManyField(Group, related_name='groupUsers')

正向查询:

  1. # 查询用户隶属组
  2. _t = User.objects.get(username = '运维咖啡吧')
  3. _t.groups.all()

反向查询:

  1. # 查询组包含用户
  2. _t = Group.objects.get(name = 'groupC')
  3. _t.user_set.all()

同样M2M字段如果有related_name属性,那么可以直接用下边的方式反查

  1. _t = Group.objects.get(name = 'groupC')
  2. _t.groupUsers.all()

get_object_or_404

正常如果我们要去数据库里搜索某一条数据时,通常使用下边的方法:

  1. _t = User.objects.get(id=734)

但当id=724的数据不存在时,程序将会抛出一个错误

  1. abcer.models.DoesNotExist: User matching query does not exist.

为了程序兼容和异常判断,我们可以使用下边两种方式:

方式一:get改为filter

  1. _t = User.objects.filter(id=724)
  2. # 取出_t之后再去判断_t是否存在

方式二:使用get_object_or_404

  1. from django.shortcuts import get_object_or_404
  2. _t = get_object_or_404(User, id=724)
  3. # get_object_or_404方法,它会先调用django的get方法,如果查询的对象不存在的话,则抛出一个Http404的异常

实现方法类似于下边这样:

  1. from django.http import Http404
  2. try:
  3. _t = User.objects.get(id=724)
  4. except User.DoesNotExist:
  5. raise Http404

get_or_create

顾名思义,查找一个对象如果不存在则创建,如下:

  1. object, created = User.objects.get_or_create(username='运维咖啡吧')

返回一个由object和created组成的元组,其中object就是一个查询到的或者是被创建的对象,created是一个表示是否创建了新对象的布尔值

实现方式类似于下边这样:

  1. try:
  2. object = User.objects.get(username='运维咖啡吧')
  3. created = False
  4. exception User.DoesNoExist:
  5. object = User(username='运维咖啡吧')
  6. object.save()
  7. created = True
  8. returen object, created

执行原生SQL

Django中能用ORM的就用它ORM吧,不建议执行原生SQL,可能会有一些安全问题,如果实在是SQL太复杂ORM实现不了,那就看看下边执行原生SQL的方法,跟直接使用pymysql基本一致了

  1. from django.db import connection
  2. with connection.cursor() as cursor:
  3. cursor.execute('select * from accounts_User')
  4. row = cursor.fetchall()
  5. return row

注意这里表名字要用app名+下划线+model名的方式

本文内容来自群友的公众号:运维咖啡吧 ,欢迎大家关注,原文地址:https://mp.weixin.qq.com/s/JVh4UnS2Tql9gUVaBSoGuA

Django model select的各种用法详解的更多相关文章

  1. AngularJS select中ngOptions用法详解

    AngularJS select中ngOptions用法详解   一.用法 ngOption针对不同类型的数据源有不同的用法,主要体现在数组和对象上. 数组: label for value in a ...

  2. Django model 中的 class Meta 详解

    Django model 中的 class Meta 详解 通过一个内嵌类 "class Meta" 给你的 model 定义元数据, 类似下面这样: class Foo(mode ...

  3. Django model中的class Meta详解

    通过一个内嵌类 "class Meta" 给你的 model 定义元数据, 类似下面这样: class Foo(models.Model): bar = models.CharFi ...

  4. Django model中的 class Meta 详解

    通过一个内嵌类 "class Meta" 给你的 model 定义元数据, 类似下面这样: class Foo(models.Model): bar = models.CharFi ...

  5. Django框架 之 ORM查询操作详解

    Django框架 之 ORM查询操作详解 浏览目录 一般操作 ForeignKey操作 ManyToManyField 聚合查询 分组查询 F查询和Q查询 事务 Django终端打印SQL语句 在Py ...

  6. Vue1.0用法详解

    Vue.js 不支持 IE8 及其以下版本,因为 Vue.js 使用了 IE8 不能实现的 ECMAScript 5 特性. 开发环境部署 可参考使用 vue+webpack. 基本用法 1 2 3 ...

  7. @RequestMapping 用法详解之地址映射

    @RequestMapping 用法详解之地址映射 引言: 前段时间项目中用到了RESTful模式来开发程序,但是当用POST.PUT模式提交数据时,发现服务器端接受不到提交的数据(服务器端参数绑定没 ...

  8. jQuery 事件用法详解

    jQuery 事件用法详解 目录 简介 实现原理 事件操作 绑定事件 解除事件 触发事件 事件委托 事件操作进阶 阻止默认事件 阻止事件传播 阻止事件向后执行 命名空间 自定义事件 事件队列 jque ...

  9. SQL中CONVERT()函数用法详解

    SQL中CONVERT函数格式: CONVERT(data_type,expression[,style]) 参数说明: expression 是任何有效的 Microsoft® SQL Server ...

随机推荐

  1. 4、python常用基础类型介绍

    1.字符串 str 描述性质的一种表示状态的例如名字 word='helloworld' print(type(word),word) <class 'str'> helloworld2. ...

  2. azkaban 配置邮件

    1.配置邮件请在azkaban-web-server中进行配置:如下图:      /opt/azkaban/azkaban/azkaban-web-server/build/install/azka ...

  3. 在ASP.NET MVC中使用Area区域

    在大型的ASP.NET mvc5项目中一般都有许多个功能模块,这些功能模块可以用Area(中文翻译为区域)把它们分离开来,比如:Admin,Customer,Bill.ASP.NET MVC项目中把各 ...

  4. python 路径处理

    1.分解路径名 比如要把xxx/yyy/zzz.py 分解成文件名和目录 两种方法: 一.os.path.split(file) 二.os.path.basename()  ;   os.path.d ...

  5. sys、os 模块

    sys 模块常见函数 sys.argv           #命令行参数List,第一个元素是程序本身路径 sys.exit(n)        #退出程序,正常退出时exit(0) sys.vers ...

  6. mysql linux安装

    Mysql(使用版本5.7.25) 1.  检查是否已安装 #rpm -qa|grep -i mysql 2.  下载安装包 网址:https://dev.mysql.com/downloads/my ...

  7. Python开发【第五篇】:模块

    递归的案例:阶乘 1*2*3*4*5*6*7- def func(num):     if num == 1:         return 1     return num * func(num - ...

  8. EF多字段求和(分组/不分组)

    分组多字段求和 query.GroupBy(q => new { q.Year, q.Month }) .Select(q => new { Year = q.Key.Year, Mont ...

  9. 89. Gray Code返回位运算的所有生成值

    [抄题]: The gray code is a binary numeral system where two successive values differ in only one bit. G ...

  10. [leetcode]42. Trapping Rain Water雨水积水问题

    Given n non-negative integers representing an elevation map where the width of each bar is 1, comput ...