基本操作
-
# 获取所有数据,对应SQL:select * from User
-
-
-
# 匹配,对应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
-
常用操作
-
# 获取总数,对应SQL:select count(1) from User
-
-
-
# 获取总数,对应SQL:select count(1) from User where name =
-
User.objects.filter(name=
-
-
# 大于,>,对应SQL:select * from User where id > 724
-
User.objects.filter(id__gt=724)
-
-
# 大于等于,>=,对应SQL:select * from User where id >= 724
-
User.objects.filter(id__gte=724)
-
-
# 小于,<,对应SQL:select * from User where id < 724
-
User.objects.filter(id__lt=724)
-
-
# 小于等于,<=,对应SQL:select * from User where id <= 724
-
User.objects.filter(id__lte=724)
-
-
# 同时大于和小于, 1 < id < 10,对应SQL:select * from User where id > 1 and id < 10
-
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])
-
-
# 不包含,not in,对应SQL:select * from User where id not in (11,22,33)
-
User.objects.exclude(id__in=[11, 22, 33])
-
-
# 为空:isnull=True,对应SQL:select * from User where pub_date is null
-
User.objects.filter(pub_date__isnull=True)
-
-
# 不为空:isnull=False,对应SQL:select * from User where pub_date is not null
-
User.objects.filter(pub_date__isnull=True)
-
-
# 匹配,like,大小写敏感,对应SQL:select * from User where name like
-
User.objects.filter(name__contains="sre")
-
-
# 匹配,like,大小写不敏感,对应SQL:select * from User where name like
-
User.objects.filter(name__icontains="sre")
-
-
# 不匹配,大小写敏感,对应SQL:select * from User where name not like
-
User.objects.exclude(name__contains="sre")
-
-
# 不匹配,大小写不敏感,对应SQL:select * from User where name not like
-
User.objects.exclude(name__icontains="sre")
-
-
# 范围,between and,对应SQL:select * from User where id between 3 and 8
-
User.objects.filter(id__range=[3, 8])
-
-
# 以什么开头,大小写敏感,对应SQL:select * from User where name like
-
User.objects.filter(name__startswith=
-
-
# 以什么开头,大小写不敏感,对应SQL:select * from User where name like
-
User.objects.filter(name__istartswith=
-
-
# 以什么结尾,大小写敏感,对应SQL:select * from User where name like
-
User.objects.filter(name__endswith=
-
-
# 以什么结尾,大小写不敏感,对应SQL:select * from User where name like
-
User.objects.filter(name__iendswith=
-
-
# 排序,order by,正序,对应SQL:select * from User where name =
-
User.objects.filter(name=
-
-
# 多级排序,order by,先按name进行正序排列,如果name一致则再按照id倒叙排列
-
User.objects.filter(name=
-
-
# 排序,order by,倒序,对应SQL:select * from User where name =
-
User.objects.filter(name=
进阶操作
-
-
-
-
-
-
-
-
User.objects.all()[10:20]
-
-
-
from django.db.models import Count
-
User.objects.values_list(‘username‘).annotate(Count(‘id‘))
-
-
-
User.objects.values(‘username‘).distinct().count()
-
-
-
User.objects.values_list(‘username‘, ‘fullname‘)
-
-
-
User.objects.values_list(‘username‘, flat=True)
-
-
-
from django.db.models import Sum,Count,Max,Min,Avg
-
-
User.objects.aggregate(Count(‘id’))
-
User.objects.aggregate(Sum(‘age’))
时间字段
-
-
User.objects.filter(create_time__date=datetime.date(2018, 8, 1))
-
User.objects.filter(create_time__date__gt=datetime.date(2018, 8, 2))
-
-
-
User.objects.filter(create_time__year=2018)
-
User.objects.filter(create_time__year__gte=2018)
-
-
-
User.objects.filter(create_time__month__gt=7)
-
User.objects.filter(create_time__month__gte=7)
-
-
-
User.objects.filter(create_time__day=8)
-
User.objects.filter(create_time__day__gte=8)
-
-
-
User.objects.filter(create_time__week_day=2)
-
User.objects.filter(create_time__week_day__gte=2)
-
-
-
User.objects.filter(create_time__hour=9)
-
User.objects.filter(create_time__hour__gte=9)
-
-
-
User.objects.filter(create_time__minute=15)
-
User.objects.filter(create_time__minute_gt=15)
-
-
-
User.objects.filter(create_time__second=15)
-
User.objects.filter(create_time__second__gte=15)
-
-
-
-
today = datetime.date.today()
-
-
deploy_date_count = Task.objects.filter(
-
create_time__range=(today - datetime.timedelta(days=7), today)
-
).extra(select=select).values(
Q 的使用
Q对象可以对关键字参数进行封装,从而更好的应用多个查询,可以组合&(and)、|(or)、~(not)操作符。
例如下边的语句
-
from django.db.models import Q
-
-
-
Q(role__startswith=‘sre_‘),
-
Q(name=‘公众号‘) | Q(name=‘运维咖啡吧‘)
-
转换成SQL语句如下:
select * from User where role like ‘sre_%‘ and (name=‘公众号‘ or name=‘运维咖啡吧‘)
通常更多的时候我们用Q来做搜索逻辑,比如前台搜索框输入一个字符,后台去数据库中检索标题或内容中是否包含
-
-
-
-
-
-
-
-
-
-
外键: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.objects.get(name=‘Role03‘)
-
-
_t = Role.objects.get(name=‘Role03‘)
-
-
-
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‘)
-
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 = Group.objects.get(name =
-
同样M2M字段如果有related_name
属性,那么可以直接用下边的方式反查
-
_t = Group.objects.get(name =
-
get_object_or_404
正常如果我们要去数据库里搜索某一条数据时,通常使用下边的方法:
_t = User.objects.get(id=734)
但当id=724
的数据不存在时,程序将会抛出一个错误
abcer.models.DoesNotExist: User matching query does not exist.
为了程序兼容和异常判断,我们可以使用下边两种方式:
-
_t = User.objects.filter(id=724)
-
-
from django.shortcuts import get_object_or_404
-
-
_t = get_object_or_404(User, id=724)
-
实现方法类似于下边这样:
-
from django.http import Http404
-
-
-
_t = User.objects.get(id=724)
-
except User.DoesNotExist:
-
get_or_create
顾名思义,查找一个对象如果不存在则创建,如下:
object, created = User.objects.get_or_create(username=‘运维咖啡吧‘)
返回一个由object和created组成的元组,其中object就是一个查询到的或者是被创建的对象,created是一个表示是否创建了新对象的布尔值
实现方式类似于下边这样:
-
-
object = User.objects.get(username=
-
-
-
exception User.DoesNoExist:
-
-
-
-
-
-
执行原生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‘)
-
-
-