1. 程式人生 > >django model 條件過濾 queryset.filter(**condtions) 用法

django model 條件過濾 queryset.filter(**condtions) 用法

gte datetime food dsw ood objects name 去重復 art

1、下述代碼查詢model對應數據庫中日期等於2018-05-22的數據:

queryset = model.objects.all()

condtions: {‘date‘: ‘2018-05-22‘}

query_res = queryset.filter(**condtions)

2、下述代碼查詢model對應數據庫中日期小於2018-05-22的數據:

queryset = model.objects.all()

condtions: {‘date__lt‘: ‘2018-05-22‘}

query_res = queryset.filter(**condtions)

3.總結:條件選取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

如果參數是字典,如

condtions: {‘date__lt‘: ‘2018-05-22‘,‘status‘: ‘未支付‘,‘name__exact‘: ‘yangxia‘}

Entry.objects.filter(**condtions)相當於 Entry.objects.filter(date__lt= ‘2018-05-22‘,status=‘未支付‘,name__exact=‘yangxia‘)

翻譯成sql語句是

select * from Entry.objects where date<=‘2018-05-22‘ and status=‘未支付‘ and name like ‘yangxia‘


filter例子:
>> q1 = Entry.objects.filter(headline__startswith="What")
>> q2= q1.filter(pub_date__gte=datetime.date.today())
>>> q3= q.filter(pub_date__lte=datetime.date.today())

exclude例子:
>>> q1 = q.exclude(body_text__icontains="food")

>> q2 = q1.exclude(pub_date__gte=datetime.date.today())

django model 條件過濾 queryset.filter(**condtions) 用法