在Django中有相当多的操作是通过双下划线与动作连接起来使用,为了以后更加方便的查找和使用,现在总结以下Django中基本的双下划线操作
比较符:大于--gt 小于--lt 等于--eq 大于等于--gte 小于等于--lte
models.Example.objects.filter(id__gt=1) # 获取id大于1的值
models.Example.objects.filter(id__gte=1) # 获取id大于等于1的值
models.Example.objects.filter(id__lt=10) # 获取id小于10的值
models.Example.objects.filter(id__lte=10) # 获取id小于10的值
models.Example.objects.filter(id__lt=10, id__gt=1) # 获取id大于1 且 小于10的值
范围操作符:
包含-- in 在范围内--range
models.Example.objects.filter(id__in=[11, 22, 33]) # 获取id等于11、22、33的数据
models.Example.objects.exclude(id__in=[11, 22, 33]) # not in 实际上是exclude的函数生效
包括--contain
models.Example.objects.filter(name__contains="ven")
models.Example.objects.filter(name__icontains="ven") # icontains大小写不敏感
models.Example.objects.exclude(name__icontains="ven")
在范围内--range
models.Example.objects.filter(id__range=[1, 2]) # 范围bettwen 1 and 2
匹配操作符
为空--isnull
Entry.objects.filter(pub_date__isnull=True)
字符匹配:startswith,istartswith, endswith, iendswith, ‘i代表大小写不敏感’
类操作符:
对某一类进行排序--order by
models.Example.objects.filter(name='seven').order_by('id') # asc 升序
models.Example.objects.filter(name='seven').order_by('-id') # desc降序
对某一类进行归类--group by
from django.db.models import Count, Min, Max, Sum
models.Example.objects.filter(c1=1).values('id').annotate(c=Count('num'))
SELECT "app01_Example"."id", COUNT("app01_Example"."num") AS "c" FROM "app01_Example" WHERE "app01_Example"."c1" = 1 GROUP BY "app01_Example"."id"
正则匹配 regex iregex(不区分大小写)
Entry.objects.get(title__regex=r'^(An?|The) +')
Entry.objects.get(title__iregex=r'^(an?|the) +')
日期相关 date year month day week_day hour minute second
Entry.objects.filter(pub_date__date=datetime.date(2017, 1, 1))
Entry.objects.filter(pub_date__date__gt=datetime.date(2017, 1, 1)) Entry.objects.filter(pub_date__year=2017)
Entry.objects.filter(pub_date__year__gte=2017) Entry.objects.filter(pub_date__month=12)
Entry.objects.filter(pub_date__month__gte=6) Entry.objects.filter(pub_date__day=3)
Entry.objects.filter(pub_date__day__gte=3) Entry.objects.filter(pub_date__week_day=2)
Entry.objects.filter(pub_date__week_day__gte=2) Event.objects.filter(timestamp__hour=23)
Event.objects.filter(time__hour=5)
Event.objects.filter(timestamp__hour__gte=12) Event.objects.filter(timestamp__minute=29)
Event.objects.filter(time__minute=46)
Event.objects.filter(timestamp__minute__gte=29) Event.objects.filter(timestamp__second=31)
Event.objects.filter(time__second=2)
Event.objects.filter(timestamp__second__gte=31)