1. 程式人生 > 實用技巧 >Django Q查詢

Django Q查詢

1、基本與查詢

from django.db.models import Q
q1 = Q()
q1.connector = 'AND'
q1.children.append(('sex', '男'))
q1.children.append(('age', 23))

objs = Student.objects.filter(q1)

2、基本或查詢

from django.db.models import Q

q1 = Q()
q1.connector = 'OR'
q1.children.append(('name', '張良'))
q1.children.append(('name'
, '李白')) q1.children.append(('name', '魏莊')) objs = Student.objects.filter(q1)

3、合併查詢

參考https://blog.csdn.net/qq_41000891/article/details/84501540

from django.db.models import Q
 
con = Q()
q1 = Q()
q1.connector = "AND"
q1.children.append(("email", "[email protected]"))
q1.children.append(("password", "abc123"))
 
q2 
= Q() q2.connector = "AND" q2.children.append(("username", "abc")) q2.children.append(("password", "xyz123")) con.add(q1, "OR") con.add(q2, "OR") obj = models.UserInfo.objects.filter(con).first() # 查詢[email protected]和password=abc123 或者 username=abc和password=xyz123的使用者資訊

4、查詢關鍵字

參考https://blog.csdn.net/u012643122/article/details/52751073

__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