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


  在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)

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM