Django ORM query operation

Common filter operation

Greater than, greater than or equal:

__gt greater than>
__gte greater than or equal> =

Student.objects.filter (age__gt = 10) // Query older than 10 year-old student
Student.objects.filter (age__gte = 10) // Query older than or equal to 10-year-old student

special attention: underline here is double underlined, are also following the introduction of double-underlined.
Less than, less than or equal:

__lt less than <
__lte Less than or equal <=

Student.objects.filter (age__lt = 10) // Query students younger than 10 years old
Student.objects.filter (age__lte = 10) // query aged less than or equal to 10-year-old student
like:

__exact exactly equal like 'AAA'
__iexact ignore case exactly equal iLike 'AAA'
__contains comprises like '%% AAA'
__icontains, ignore the case ilike '% aaa%', but for sqlite, it contains effect equivalent to icontains.
in:

__in

query aged students a range of
Student.objects.filter (age__in = [10, 20, 30])
IS null / IS not null:

__isnull sentenced empty

Student.objects.filter (name__isnull = True) // queries the user name is blank student
Student.objects.filter (name__isnull = False) // queries the user name is not empty of students
is not equal to / is not included in:

Student.objects.filter (). Excute (age = 10) // query the age of 10 are not students of
Student.objects.filter (). Excute (age__in = [10, 20]) // query is not the age of [10, 20 ] students
other common fuzzy queries:

__startswith to begin with ...
__istartswith beginning to ... ignore case
__endswith to ... end
__iendswith ending ..., ignore case
__range within ... range
__year year date field
__month month date field
day __day date field of
multi-table join query:

 A class (models.Model):
    name = models.CharField (U 'name')
 class B (models.Model):
    AA = models.ForeignKey (A)

B.objects.filter (aa__name__contains = 'searchtitle') query # B table aa foreign key columns in the table corresponding to table B contains the name of the object searchtitle.

Query 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):       对查询结果排序
  
< 6 > reverse():              对查询结果反向排序
  
< 8 > count():                返回数据库中匹配查询(QuerySet)的对象数量。
  
< 9 > first():                返回第一条记录
  
< 10 > last():                返回最后一条记录
  
< 11 > exists():              如果QuerySet包含数据,就返回 True ,否则返回 False
 
< 12 > values( * field):        返回一个ValueQuerySet——一个特殊的QuerySet,运行后得到的并不是一系列
                             model的实例化对象,而是一个可迭代的字典序列
< 13 > values_list( * field):   它与values()非常相似,它返回的是一个元组序列,values返回的是一个字典序列
 
< 14 > distinct():            从返回结果中剔除重复纪录

Guess you like

Origin www.cnblogs.com/ls1997/p/10955402.html