单表查询之神奇的双下划线:
单表查询之神奇的双下划线
models.Tb1.objects.filter(id__lt=10, id__gt=1) # 获取id大于1 且 小于10的值 models.Tb1.objects.filter(id__in=[11, 22, 33]) # 获取id等于11、22、33的数据 models.Tb1.objects.exclude(id__in=[11, 22, 33]) # not in models.Tb1.objects.filter(name__contains="ven") # 获取name字段包含"ven"的 models.Tb1.objects.filter(name__icontains="ven") # icontains大小写不敏感 models.Tb1.objects.filter(id__range=[1, 3]) # id范围是1到3的,等价于SQL的bettwen and 类似的还有:startswith,istartswith, endswith, iendswith date字段还可以: models.Class.objects.filter(first_day__year=2017)
代码示例:
1 import os 2 3 if __name__ == '__main__': 4 #加载Djang00项目的配置信息 5 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ormday69.settings") 6 #导入Django,并启动Django项目 7 import django 8 django.setup() 9 10 from app01 import models11 12 13 14 15 #单表查询之神奇的双下划线16 #查询id值大于1小于4的值17 ret = models.Person.objects.filter(id__lt=4,id__gt=1)18 print(ret)19 #in20 #查询id在[1,3,5,7]中的结果21 ret = models.Person.objects.filter(id__in = [1,3,5,7])22 print(ret)23 ret = models.Person.objects.exclude(id__in=[1, 3, 5, 7])24 print(ret)25 #contains 字段包含指定值的26 #icontains 忽略大小写包含指定值27 ret = models.Person.objects.filter(name__contains="小")28 print(ret)29 #range30 #判断id值在哪个区间的SQL语句 between and 1<= <=331 ret = models.Person.objects.filter(id__range=[1,3])32 print(ret)33 #日期和事件段还可以有以下写法34 ret = models.Person.objects.filter(birthday__year=2000)35 print(ret)36 ret = models.Person.objects.filter(birthday__year=2000,birthday__month=5)37 print(ret)