Model中的F
F 的操作通常的应用场景在于:公司对于每个员工,都涨500的工资。这个时候F就可以作为查询条件
|
1
2
3
|
from django.db.models import Fmodels.UserInfo.objects.filter().update(salary=F('salary')+500)# F('salary')就表示salary在这行记录中的值。 |
F的使用场景基本就是这样,比较简单。
Model中的Q
Q 的操作通常的应用场景在于:构造搜索条件。
普通filter搜索条件支持三种传参方式:1. 传具体参数 2.传字典 3.传Q对象。具体例子如下
1. 传具体参数
|
1
|
models.UserInfo.objects.filter(id=3,name='Bob') |
2. 传字典
|
1
2
|
dic = {'id':3,'name':'Bob'}models.UserInfo.objects.filter(**dic) |
3. 传Q对象--通常会用在进行构造组合搜索
步骤显示:
|
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
27
28
29
30
31
32
33
|
类型一: 构建简单搜索条件# 1. 导入Q模块from django.db.models import Q# 2. 传入条件进行查询q1 = Q() # 创建Q对象实例q1.connector = 'OR' # 多个条件之间以or形式连接q1.children.append(('id', 1)) q1.children.append(('id', 2))q1.children.append(('id', 3)) models.Tb1.objects.filter(q1) # 传入简单的Q对象进行查询,每个查询条件之间以or连接#--------------------------------------------------------------------------------#类型二:构建复杂搜索条件# 1. 导入Q模块from django.db.models import Q# 2. 创建Q对象实例con = Q()# 3. 创建条件q1q1 = Q()q1.connector = 'OR'q1.children.append(('id', 1)) # 这三个条件以or的形式连接q1.children.append(('id', 2))q1.children.append(('id', 3))# 4. 创建条件q2q2 = Q()q2.connector = 'OR'q2.children.append(('status', '在线'))# 5. 指定不同搜索条件之间以and还是or来连接con.add(q1, 'AND')con.add(q2, 'AND') # 表示q1与q2之间通过and来连接models.Tb1.objects.filter(con) #传入复杂Q对象进行搜索 |