Django中下劃線的用法介紹(一)

  在Django中有至關多的操做是經過雙下劃線與動做鏈接起來使用,爲了之後更加方便的查找和使用,如今總結如下Django中基本的雙下劃線操做python

  比較符:大於--gt  小於--lt 等於--eq  大於等於--gte 小於等於--ltedjango

  

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的值

   範圍操做符:app

包含-- in   在範圍內--range函數

models.Example.objects.filter(id__in=[11, 22, 33])   # 獲取id等於十一、2二、33的數據
models.Example.objects.exclude(id__in=[11, 22, 33])  # not in 其實是exclude的函數生效

包括--containspa

models.Example.objects.filter(name__contains="ven")
models.Example.objects.filter(name__icontains="ven") # icontains大小寫不敏感
models.Example.objects.exclude(name__icontains="ven")

 在範圍內--rangeblog

models.Example.objects.filter(id__range=[1, 2])   # 範圍bettwen 1 and 2

 

  匹配操做符排序

爲空--isnullget

Entry.objects.filter(pub_date__isnull=True)

 字符匹配:startswith,istartswith, endswith, iendswith,  ‘i表明大小寫不敏感’it

 

  類操做符:class

對某一類進行排序--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)
相關文章
相關標籤/搜索