Django ORM 模糊查詢和查詢操作
queryset中支持鏈式操作
book=Book.objects.all().order_by('-nid').first()
只要返回的是queryset對象就可以調用其他的方法,直到返回的是對象本身
模糊查詢常用的操作
大於、大於等於:
__gt 大於>
__gte 大於等於>=
Student.objects.filter(age__gt=10) // 查詢年齡大於10歲的學生
Student.objects.filter(age__gte=10) // 查詢年齡大於等於10歲的學生
特別注意:這里的下划線是雙下划線,下面將介紹的也都是雙下划線。
小於、小於等於:
__lt 小於<
__lte 小於等於<=
Student.objects.filter(age__lt=10) // 查詢年齡小於10歲的學生
Student.objects.filter(age__lte=10) // 查詢年齡小於等於10歲的學生
like:
__exact 精確等於 like 'aaa'
__iexact 精確等於 忽略大小寫 ilike 'aaa'
__contains 包含 like '%aaa%'
__icontains 包含,忽略大小寫 ilike '%aaa%',但是對於sqlite來說,contains的作用效果等同於icontains。
in:
__in
查詢年齡在某一范圍的學生
Student.objects.filter(age__in=[10, 20, 30])
is null / is not null:
__isnull 判空
Student.objects.filter(name__isnull=True) // 查詢用戶名為空的學生
Student.objects.filter(name__isnull=False) // 查詢用戶名不為空的學生
不等於/不包含於:
Student.objects.filter().excute(age=10) // 查詢年齡不為10的學生
Student.objects.filter().excute(age__in=[10, 20]) // 查詢年齡不在 [10, 20] 的學生
其他常用模糊查詢:
__startswith 以…開頭
__istartswith 以…開頭 忽略大小寫
__endswith 以…結尾
__iendswith 以…結尾,忽略大小寫
__range 在…范圍內
__year 日期字段的年份
__month 日期字段的月份
__day 日期字段的日
Book.objects.filter(create_time__year=2019, create_time__month=4).all()
如果是mysql數據庫settings里面修改 USE_TZ = False
多表連接查詢:
class A(models.Model):
name = models.CharField(u'名稱')
class B(models.Model):
aa = models.ForeignKey(A)
B.objects.filter(aa__name__contains='searchtitle')#查詢B表中外鍵aa所對應的表中字段name包含searchtitle的B表對象。
查詢API
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
<
1
>
all
(): 查詢所有結果
<
2
>
filter
(
*
*
kwargs): 它包含了與所給篩選條件相匹配的對象
<
3
> get(
*
*
kwargs): 返回與所給篩選條件相匹配的對象,返回結果有且只有一個,
如果符合篩選條件的對象超過一個或者沒有都會拋出錯誤。
<
4
> exclude(
*
*
kwargs): 它包含了與所給篩選條件不匹配的對象
<
5
> order_by(
*
field): 對查詢結果排序 用法:order_by('-price') DESC 降序
<
6
> reverse(): 對查詢結果反向排序
<
8
> count(): 返回數據庫中匹配查詢(QuerySet)的對象數量。
<
9
> first(): 返回第一條記錄
<
10
> last(): 返回最后一條記錄
<
11
> exists(): 如果QuerySet包含數據,就返回
True
,否則返回
False 相當於limit 1(用途查詢這個表中是否有值)
<
12
> values(
*
field):
用法:Book.objects.all.values('title','price') 返回值是<queryset[{'title':'aa','pirce':12},{}]
<
13
> values_list(
*
field):
<
14
> distinct(): 從返回結果中剔除重復紀錄 用法:Book.objects.all.values('title','price').distinct()
錯誤用法 Book.objects.all.distinct() 因為id不相同,其他相同,無法去重
|