# 过滤 filter() data = Users.objects.filter(sex=0) data = Users.objects.filter(sex=0,age=22) data = Users.objects.filter(sex=0).filter(age=26)
#排除 exclude() data = Users.objects.exclude(sex=0)
# 排序 order_by() data = Users.objects.all().order_by('-id')
# values() 一个对象构成一个字典,然后构成一个列表返回,限制返回的字段 data = Users.objects.all().values() data = Users.objects.all().values('id','username','age')
返回单个值的方法 只能返回一个结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# get() 获取一个对象 data = Users.objects.get(id=1) data = Users.objects.get(age=1) X data = Users.objects.get(sex=0) X
''' get如果查询不到符合条件的数据 则抛出异常 DoesNotExist at /demo/ Users matching query does not exist. get如果查询到多条数据,抛出异常 MultipleObjectsReturned at /demo/ get() returned more than one Users -- it returned 2! ''' # count() 统计并返回查询条件的总条数 data = Users.objects.all() print(data.count())
# first last data = Users.objects.filter(sex=0).last() data = Users.objects.filter(sex=0).first()
# exists() 检测查询条件的数据是否存在 data = Users.objects.filter(sex=2).exists()
其它查询
1 2 3 4 5
#限制级查询 #查询的前五个 data = Users.objects.all()[:5] #查询的第六个到第十个 data = Users.objects.all()[5:10]
1 2
# 比较运算符 data = Users.objects.filter(age__gt=20)
1 2 3 4 5 6 7 8
#包含查询 like 模糊查询 # select * from user where name like '%admin%'; data = Users.objects.filter(username__contains='a') data = Users.objects.filter(username__icontains='a')
#以‘a’开头或者结尾,关键词如上加i表示不区分大小写 data = Users.objects.filter(username__startswith='a') data = Users.objects.filter(username__endswith='a')
1 2 3
#是否为空,后面的False是说为空为假 data = Users.objects.filter(username__isnull=False) data = Users.objects.filter(username__isnotnull=False)
1 2 3
# in # select * from user where id in 1,23 data = Users.objects.filter(id__in=[1,23])
1 2 3 4 5
# or # select * from users where username like '%ab%' or age like '%ab%' or email like '%ab%'; from django.db.models import Q data = Users.objects.filter(Q(username__contains='ab')|Q(age__contains='ab')|Q(email__contains='ab')) print(data)