1. 程式人生 > >Django models filter篩選條件

Django models filter篩選條件

條件選取querySet的時候,filter表示=,exclude表示!=。
querySet.distinct() 去重複
__exact 精確等於 like 'aaa'
 __iexact 精確等於 忽略大小寫 ilike 'aaa'
 __contains 包含 like '%aaa%'
 __icontains 包含 忽略大小寫 ilike '%aaa%',但是對於sqlite來說,contains的作用效果等同於icontains。
__gt 大於
__gte 大於等於
__lt 小於
__lte 小於等於
__in 存在於一個list範圍內
__startswith 以...開頭
__istartswith 以...開頭 忽略大小寫
__endswith 以...結尾
__iendswith 以...結尾,忽略大小寫
__range 在...範圍內
__year 日期欄位的年份
__month 日期欄位的月份
__day 日期欄位的日
__isnull=True/False

 

例q1.filter(pub_date__gte=datetime.date.today())表示為時間>=now,q1.exclude(pub_date__gte=datetime.date.today())表示為<=now

 

“在django models中取得一個欄位的distinct值”。就是select distinct xxx from table_name ...這樣的功能。使用values會生成ValuesQuerySet(形如N個dict組成的list),猜測大資料無額外效能影響,畢竟queryset系列都是使用時才查詢操作的。
xxxx.objects.values("field_name").distinct() 或者 xxxx.objects.distinct().values("field_name")