1. 程式人生 > >Django 字段查詢謂詞表

Django 字段查詢謂詞表

等於 範圍 table blog 查詢 head get() sql語句 this

Django 字段查詢謂詞表

謂詞 含義 示例 等價SQL語句
exact 精確等於 Comment.objects.filter(id__exact=14) select * from Comment where id=14
iexact 大小寫不敏感的等於 Comment.objects.filter(headline__iexact=’I like this’) select * from Comment where upper(headline)=’I LIKE THIS’
contains 模糊匹配 Comment.objects.filter(headline__contains=’good’) select * from Comment where headline like “%good%”
in 包含 Comment.objects.filter(id__in=[1,5,9]) select * from Comment where id in (1,5,9)
gt 大於 Comment.objects.filter(n_visits__gt=30) select * from Comment where n_visits>30
gte 大於等於 Comment.objects.filter(n_visits__gte=30) select * from COmment where n_visits>=30
lt 小於
lte 小於等於
startswith 以…開頭 Comment.objects.filter(body_text__startswith=”Hello”) select * from Comment where body_text like ‘Hello%’
endswith 以…結尾
range 在…範圍內 start_date=datetime.date(2015,1,1)
end_date=datetime.date(2015.2.1)
Comment.objects.filter(
pub_date__range=(start_date,end_date)
)
select * from Comment
where pub_date
between ‘2015-1-1’ and ‘2015-2-1’
year Comment.objects.filter(
pub_date__year=2015
)
select * from Comment
where pub_date
between ‘2015-1-1 0:0:0’
and ‘2015-12-31 23:59:59’
month
day
week_day 星期幾
isnull 是否為空 Comment.objects.filter(
pub_date__isnull=True
)
select * from Comment where
pub_date is NULL

filter(**kwargs): 返回符合篩選條件的數據集

exclude(**kwargs): 返回不符合篩選條件的數據集

Comment.objects.filter(pub_date__year=2015)

多個filter和exclude可以鏈接在一起查詢

Comment.objects.filter(pub_date__year=2015).exclude(pub_date__month=1).exclude(n_visits__exact=0)

get() :查詢單條記錄,註意沒有查詢到數據的時候會報錯

Comment.objects.get(id_exact=1)

all(): 查詢所有數據

Comment.objects.all()
Comment.objects.all()[:10]
Comment.objects.all[10:20]

order_by(): 排序

Comment.objects.order_by(headline)

Django 字段查詢謂詞表