欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Django model select的各种用法示例介绍

程序员文章站 2024-02-03 11:42:22
前言 《django model update的各种用法介绍》文章介绍了django model的各种update操作,这篇文章就是她的姊妹篇,详细介绍django mo...

前言

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

基本操作

# 获取所有数据,对应sql:select * from user
user.objects.all()

# 匹配,对应sql:select * from user where name = '运维咖啡吧'
user.objects.filter(name='运维咖啡吧')

# 不匹配,对应sql:select * from user where name != '运维咖啡吧'
user.objects.exclude(name='运维咖啡吧')

# 获取单条数据(有且仅有一条,id唯一),对应sql:select * from user where id = 724
user.objects.get(id=123)

常用操作

# 获取总数,对应sql:select count(1) from user
user.objects.count()
user.objects.filter(name='运维咖啡吧').count()

# 比较,gt:>,gte:>=,lt:<,lte:<=,对应sql:select * from user where id > 724
user.objects.filter(id__gt=724)
user.objects.filter(id__gt=1, id__lt=10)

# 包含,in,对应sql:select * from user where id in (11,22,33)
user.objects.filter(id__in=[11, 22, 33])
user.objects.exclude(id__in=[11, 22, 33])

# isnull:isnull=true为空,isnull=false不为空,对应sql:select * from user where pub_date is null
user.objects.filter(pub_date__isnull=true)

# like,contains大小写敏感,icontains大小写不敏感,相同用法的还有startswith、endswith
user.objects.filter(name__contains="sre")
user.objects.exclude(name__contains="sre")

# 范围,between and,对应sql:select * from user where id between 3 and 8
user.objects.filter(id__range=[3, 8])

# 排序,order by,'id'按id正序,'-id'按id倒叙
user.objects.filter(name='运维咖啡吧').order_by('id')
user.objects.filter(name='运维咖啡吧').order_by('-id')

# 多级排序,order by,先按name进行正序排列,如果name一致则再按照id倒叙排列
user.objects.filter(name='运维咖啡吧').order_by('name','-id')

进阶操作

# limit,对应sql:select * from user limit 3;
user.objects.all()[:3]

# limit,取第三条以后的数据,没有对应的sql,类似的如:select * from user limit 3,10000000,从第3条开始取数据,取10000000条(10000000大于表中数据条数)
user.objects.all()[3:]

# offset,取出结果的第10-20条数据(不包含10,包含20),也没有对应sql,参考上边的sql写法
user.objects.all()[10:20]

# 分组,group by,对应sql:select username,count(1) from user group by username;
from django.db.models import count
user.objects.values_list('username').annotate(count('id'))

# 去重distinct,对应sql:select distinct(username) from user
user.objects.values('username').distinct().count()

# filter多列、查询多列,对应sql:select username,fullname from accounts_user
user.objects.values_list('username', 'fullname')

# filter单列、查询单列,正常values_list给出的结果是个列表,里边里边的每条数据对应一个元组,当只查询一列时,可以使用flat标签去掉元组,将每条数据的结果以字符串的形式存储在列表中,从而避免解析元组的麻烦
user.objects.values_list('username', flat=true)

# int字段取最大值、最小值、综合、平均数
from django.db.models import sum,count,max,min,avg

user.objects.aggregate(count(‘id'))
user.objects.aggregate(sum(‘age'))

时间字段

# 匹配日期,date
user.objects.filter(create_time__date=datetime.date(2018, 8, 1))
user.objects.filter(create_time__date__gt=datetime.date(2018, 8, 2))


# 匹配年,year,相同用法的还有匹配月month,匹配日day,匹配周week_day,匹配时hour,匹配分minute,匹配秒second
user.objects.filter(create_time__year=2018)
user.objects.filter(create_time__year__gte=2018)

# 按天统计归档
today = datetime.date.today()
select = {'day': connection.ops.date_trunc_sql('day', 'create_time')}
deploy_date_count = task.objects.filter(
 create_time__range=(today - datetime.timedelta(days=7), today)
).extra(select=select).values('day').annotate(number=count('id'))

q 的使用

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

from django.db.models import q

user.objects.filter(
 q(role__startswith='sre_'),
 q(name='公众号') | q(name='运维咖啡吧')
)

转换成sql语句如下:

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

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

_s = request.get.get('search')

_t = blog.objects.all()
if _s:
 _t = _t.filter(
  q(title__icontains=_s) |
  q(content__icontains=_s)
 )

return _t

外键:foreignkey

表结构:

class role(models.model):
 name = models.charfield(max_length=16, unique=true)


class user(models.model):
 username = models.emailfield(max_length=255, unique=true)
 role = models.foreignkey(role, on_delete=models.cascade)

正向查询:

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

反向查询:

# 查询角色下包含的所有用户
_t = role.objects.get(name='role03')
_t.user_set.all()

另一种反向查询的方法:

_t = role.objects.get(name='role03')

# 这种方法比上一种_set的方法查询速度要快
user.objects.filter(role=_t)

第三种反向查询的方法:

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

class user(models.model):
 username = models.emailfield(max_length=255, unique=true)
 role = models.foreignkey(role, on_delete=models.cascade,related_name='roleusers')

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

_t = role.objects.get(name = 'role03')
_t.roleusers.all()

m2m:manytomanyfield

表结构:

class group(models.model):
 name = models.charfield(max_length=16, unique=true)

class user(models.model):
 username = models.charfield(max_length=255, unique=true)
 groups = models.manytomanyfield(group, related_name='groupusers')

正向查询:

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

反向查询:

# 查询组包含用户
_t = group.objects.get(name = 'groupc')
_t.user_set.all()
复制代码同样m2m字段如果有related_name属性,那么可以直接用下边的方式反查
_t = group.objects.get(name = 'groupc')
_t.groupusers.all()

get_object_or_404

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

_t = user.objects.get(id=734)

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

abcer.models.doesnotexist: user matching query does not exist.

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

方式一:get改为filter

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

方式二:使用get_object_or_404

from django.shortcuts import get_object_or_404

_t = get_object_or_404(user, id=724)
# get_object_or_404方法,它会先调用django的get方法,如果查询的对象不存在的话,则抛出一个http404的异常

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

from django.http import http404

try:
 _t = user.objects.get(id=724)
except user.doesnotexist:
 raise http404

get_or_create

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

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

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

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

try:
 object = user.objects.get(username='运维咖啡吧')
 
 created = false
exception user.doesnoexist:
 object = user(username='运维咖啡吧')
 object.save()
 
 created = true

returen object, created

执行原生sql

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

from django.db import connection

with connection.cursor() as cursor:
 cursor.execute('select * from accounts_user')
 row = cursor.fetchall()

return row

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。