extra
extra(select=None, where=None, params=None,
tables=None, order_by=None, select_params=None)
3
1
extra(select=None, where=None, params=None,
2
tables=None, order_by=None, select_params=None)
3
有些情况下,Django的查询语法难以简单的表达复杂的 WHERE 子句,对于这种情况, Django 提供了 extra() QuerySet修改机制 — 它能在 QuerySet生成的SQL从句中注入新子句
extra可以指定一个或多个 参数,例如 select, where or tables. 这些参数都不是必须的,但是你至少要使用一个!要注意这些额外的方式对不同的数据库引擎可能存在移植性问题.(因为你在显式的书写SQL语句),除非万不得已,尽量避免这样做
警告
无论何时你都需要非常小心的使用extra(). 每次使用它时,您都应该转义用户可以使用params控制的任何参数,以防止SQL注入攻击。
参数之select
The select 参数可以让你在 SELECT 从句中添加其他字段信息,它应该是一个字典,存放着属性名到 SQL 从句的映射。
queryResult=models.Article
.objects.extra(select={'is_recent': "create_time > '2017-09-05'"})
2
1
queryResult=models.Article
2
.objects.extra(select={'is_recent': "create_time > '2017-09-05'"})
结果集中每个 Entry 对象都有一个额外的属性is_recent, 它是一个布尔值,表示 Article对象的create_time 是否晚于2017-09-05.
date_list=models.Article.objects.filter(user=user_obj).extra(select={"fdate":"strftime('%%Y/%%m/%%d',create_time)"}).values_list("fdate").annotate(Count("id"))
'''
输出结果:
<QuerySet [('2017/11/22', 2), ('2017/11/24', 1)]>
'''
5
1
date_list=models.Article.objects.filter(user=user_obj).extra(select={"fdate":"strftime('%%Y/%%m/%%d',create_time)"}).values_list("fdate").annotate(Count("id"))
2
'''
3
输出结果:
4
<QuerySet [('2017/11/22', 2), ('2017/11/24', 1)]>
5
'''
参数之where / tables
您可以使用where定义显式SQL WHERE子句 - 也许执行非显式连接。您可以使用tables手动将表添加到SQL FROM子句。
where和tables都接受字符串列表。所有where参数均为“与”任何其他搜索条件。
举例来讲:
queryResult=models.Article
.objects.extra(where=['nid in (1,3) OR title like "py%" ','nid>2'])
2
1
queryResult=models.Article
2
.objects.extra(where=['nid in (1,3) OR title like "py%" ','nid>2'])
QuerySet
可切片
使用Python 的切片语法来限制查询集记录的数目 。它等同于SQL 的LIMIT 和OFFSET 子句。
>>> Entry.objects.all()[:5] # (LIMIT 5)
1
1
>>> Entry.objects.all()[:5] # (LIMIT 5)
不支持负的索引(例如Entry.objects.all()[-1])。通常,查询集 的切片返回一个新的查询集 —— 它不会执行查询。
可迭代
articleList=models.Article.objects.all()
for article in articleList:
print(article.title)
x
1
articleList=models.Article.objects.all()
2
3
for article in articleList:
4
print(article.title)
惰性查询
查询集 是惰性执行的 —— 创建查询集不会带来任何数据库的访问。你可以将过滤器保持一整天,直到查询集 需要求值时,Django 才会真正运行这个查询。
示例:
def queryTest(request):
ret=models.Article.objects.all().iterator()
for i in ret:
print(i)
return HttpResponse("ok")
输出结果:
#打印了就进行查询
'''
Quit the server with CTRL-BREAK.
(0.001) SELECT "app01_article"."id", "app01_article"."title", "app01_article"."desc", "app01_article"."read_count", "app01_article"."comment_count", "app01_article"."up_count", "app01_a
rticle"."down_count", "app01_article"."create_time", "app01_article"."category_id", "app01_article"."user_id", "app01_article"."site_article_category_id" FROM "app01_article"; args=()
bootstrap导航栏.nav与.navbar区别
[Python]循环嵌套nested loop-练习题
Java提高十五:容器元素比较Comparable&Comparator深入分析
dsds
sql
dsdsds
dsds
东京不太热
dsds
东京有点热
射太阳的人
'''
1
def queryTest(request):
2
ret=models.Article.objects.all().iterator()
3
for i in ret:
4
print(i)
5
return HttpResponse("ok")
6
输出结果:
7
#打印了就进行查询
8
'''
9
Quit the server with CTRL-BREAK.
10
(0.001) SELECT "app01_article"."id", "app01_article"."title", "app01_article"."desc", "app01_article"."read_count", "app01_article"."comment_count", "app01_article"."up_count", "app01_a
11
rticle"."down_count", "app01_article"."create_time", "app01_article"."category_id", "app01_article"."user_id", "app01_article"."site_article_category_id" FROM "app01_article"; args=()
12
bootstrap导航栏.nav与.navbar区别
13
[Python]循环嵌套nested loop-练习题
14
Java提高十五:容器元素比较Comparable&Comparator深入分析
15
dsds
16
sql
17
dsdsds
18
dsds
19
东京不太热
20
dsds
21
东京有点热
22
射太阳的人
23
'''
24
示例2:
def queryTest(request):
ret=models.Article.objects.all().iterator()
# for i in ret:
# print(i)
return HttpResponse("ok")
输出结果:
#不打印则不进行查询
不打印则不进行查询
1
def queryTest(request):
2
ret=models.Article.objects.all().iterator()
3
# for i in ret:
4
# print(i)
5
return HttpResponse("ok")
6
7
输出结果:
8
#不打印则不进行查询
缓存机制
def queryTest(request):
ret=models.Article.objects.all() #将qureyset放入一个变量
for i in ret: #然后两次循环这个变量
print(i)
for i in ret:
print(i)
return HttpResponse("ok")
输出结果:
#只查询了一次,但是打印了两次,说明第一次查询的值已经缓存到了变量中,下次直接从缓存中拿值就可以了
'''
(0.001) SELECT "app01_article"."id", "app01_article"."title", "app01_article"."desc", "app01_article"."read_count", "app01_article"."comment_count", "app01_article"."up_count", "app01_
article"."down_count", "app01_article"."create_time", "app01_article"."category_id", "app01_article"."user_id", "app01_article"."site_article_category_id" FROM "app01_article"; args=()
bootstrap导航栏.nav与.navbar区别
[Python]循环嵌套nested loop-练习题
Java提高十五:容器元素比较Comparable&Comparator深入分析
dsds
sql
dsdsds
dsds
东京不太热
dsds
东京有点热
射太阳的人
bootstrap导航栏.nav与.navbar区别
[Python]循环嵌套nested loop-练习题
Java提高十五:容器元素比较Comparable&Comparator深入分析
dsds
sql
dsdsds
dsds
东京不太热
dsds
东京有点热
射太阳的人
'''
,说明第一次查询的值已经缓存到了变量中,下次直接从缓存中拿值就可以了
x
10
1
def queryTest(request):
2
ret=models.Article.objects.all() #将qureyset放入一个变量
3
for i in ret: #然后两次循环这个变量
4
print(i)
5
for i in ret:
6
print(i)
7
return HttpResponse("ok")
8
9
10
输出结果:
11
#只查询了一次,但是打印了两次,说明第一次查询的值已经缓存到了变量中,下次直接从缓存中拿值就可以了
12
'''
13
(0.001) SELECT "app01_article"."id", "app01_article"."title", "app01_article"."desc", "app01_article"."read_count", "app01_article"."comment_count", "app01_article"."up_count", "app01_
14
article"."down_count", "app01_article"."create_time", "app01_article"."category_id", "app01_article"."user_id", "app01_article"."site_article_category_id" FROM "app01_article"; args=()
15
16
17
bootstrap导航栏.nav与.navbar区别
18
[Python]循环嵌套nested loop-练习题
19
Java提高十五:容器元素比较Comparable&Comparator深入分析
20
dsds
21
sql
22
dsdsds
23
dsds
24
东京不太热
25
dsds
26
东京有点热
27
射太阳的人
28
bootstrap导航栏.nav与.navbar区别
29
[Python]循环嵌套nested loop-练习题
30
Java提高十五:容器元素比较Comparable&Comparator深入分析
31
dsds
32
sql
33
dsdsds
34
dsds
35
东京不太热
36
dsds
37
东京有点热
38
射太阳的人
39
40
'''
优化查询
exists()与iterator()方法
exists:
extra(select=None, where=None, params=None,
tables=None, order_by=None, select_params=None)
extra(select=None, where=None, params=None,
tables=None, order_by=None, select_params=None)
有些情况下,Django的查询语法难以简单的表达复杂的 WHERE 子句,对于这种情况, Django 提供了 extra() QuerySet修改机制 — 它能在 QuerySet生成的SQL从句中注入新子句
extra可以指定一个或多个 参数,例如 select, where or tables. 这些参数都不是必须的,但是你至少要使用一个!要注意这些额外的方式对不同的数据库引擎可能存在移植性问题.(因为你在显式的书写SQL语句),除非万不得已,尽量避免这样做
警告
无论何时你都需要非常小心的使用extra(). 每次使用它时,您都应该转义用户可以使用params控制的任何参数,以防止SQL注入攻击。
参数之select
The select 参数可以让你在 SELECT 从句中添加其他字段信息,它应该是一个字典,存放着属性名到 SQL 从句的映射。
queryResult=models.Article
.objects.extra(select={'is_recent': "create_time > '2017-09-05'"})
queryResult=models.Article
.objects.extra(select={'is_recent': "create_time > '2017-09-05'"})
date_list=models.Article.objects.filter(user=user_obj).extra(select={"fdate":"strftime('%%Y/%%m/%%d',create_time)"}).values_list("fdate").annotate(Count("id"))
'''
输出结果:
<QuerySet [('2017/11/22', 2), ('2017/11/24', 1)]>
'''
date_list=models.Article.objects.filter(user=user_obj).extra(select={"fdate":"strftime('%%Y/%%m/%%d',create_time)"}).values_list("fdate").annotate(Count("id"))
'''
输出结果:
<QuerySet [('2017/11/22', 2), ('2017/11/24', 1)]>
'''
参数之where / tables
您可以使用where定义显式SQL WHERE子句 - 也许执行非显式连接。您可以使用tables手动将表添加到SQL FROM子句。
where和tables都接受字符串列表。所有where参数均为“与”任何其他搜索条件。
举例来讲:
queryResult=models.Article
.objects.extra(where=['nid in (1,3) OR title like "py%" ','nid>2'])
queryResult=models.Article
.objects.extra(where=['nid in (1,3) OR title like "py%" ','nid>2'])
可切片
>>> Entry.objects.all()[:5] # (LIMIT 5)
>>> Entry.objects.all()[:5] # (LIMIT 5)
可迭代
articleList=models.Article.objects.all()
for article in articleList:
print(article.title)
articleList=models.Article.objects.all()
for article in articleList:
print(article.title)
惰性查询
def queryTest(request):
ret=models.Article.objects.all().iterator()
for i in ret:
print(i)
return HttpResponse("ok")
输出结果:
#打印了就进行查询
'''
Quit the server with CTRL-BREAK.
(0.001) SELECT "app01_article"."id", "app01_article"."title", "app01_article"."desc", "app01_article"."read_count", "app01_article"."comment_count", "app01_article"."up_count", "app01_a
rticle"."down_count", "app01_article"."create_time", "app01_article"."category_id", "app01_article"."user_id", "app01_article"."site_article_category_id" FROM "app01_article"; args=()
bootstrap导航栏.nav与.navbar区别
[Python]循环嵌套nested loop-练习题
Java提高十五:容器元素比较Comparable&Comparator深入分析
dsds
sql
dsdsds
dsds
东京不太热
dsds
东京有点热
射太阳的人
'''
def queryTest(request):
ret=models.Article.objects.all().iterator()
for i in ret:
print(i)
return HttpResponse("ok")
输出结果:
#打印了就进行查询
'''
Quit the server with CTRL-BREAK.
(0.001) SELECT "app01_article"."id", "app01_article"."title", "app01_article"."desc", "app01_article"."read_count", "app01_article"."comment_count", "app01_article"."up_count", "app01_a
rticle"."down_count", "app01_article"."create_time", "app01_article"."category_id", "app01_article"."user_id", "app01_article"."site_article_category_id" FROM "app01_article"; args=()
bootstrap导航栏.nav与.navbar区别
[Python]循环嵌套nested loop-练习题
Java提高十五:容器元素比较Comparable&Comparator深入分析
dsds
sql
dsdsds
dsds
东京不太热
dsds
东京有点热
射太阳的人
'''
def queryTest(request):
ret=models.Article.objects.all().iterator()
# for i in ret:
# print(i)
return HttpResponse("ok")
输出结果:
#不打印则不进行查询
def queryTest(request):
ret=models.Article.objects.all().iterator()
# for i in ret:
# print(i)
return HttpResponse("ok")
输出结果:
#不打印则不进行查询
缓存机制
def queryTest(request):
ret=models.Article.objects.all() #将qureyset放入一个变量
for i in ret: #然后两次循环这个变量
print(i)
for i in ret:
print(i)
return HttpResponse("ok")
输出结果:
#只查询了一次,但是打印了两次,说明第一次查询的值已经缓存到了变量中,下次直接从缓存中拿值就可以了
'''
(0.001) SELECT "app01_article"."id", "app01_article"."title", "app01_article"."desc", "app01_article"."read_count", "app01_article"."comment_count", "app01_article"."up_count", "app01_
article"."down_count", "app01_article"."create_time", "app01_article"."category_id", "app01_article"."user_id", "app01_article"."site_article_category_id" FROM "app01_article"; args=()
bootstrap导航栏.nav与.navbar区别
[Python]循环嵌套nested loop-练习题
Java提高十五:容器元素比较Comparable&Comparator深入分析
dsds
sql
dsdsds
dsds
东京不太热
dsds
东京有点热
射太阳的人
bootstrap导航栏.nav与.navbar区别
[Python]循环嵌套nested loop-练习题
Java提高十五:容器元素比较Comparable&Comparator深入分析
dsds
sql
dsdsds
dsds
东京不太热
dsds
东京有点热
射太阳的人
'''
x
def queryTest(request):
ret=models.Article.objects.all() #将qureyset放入一个变量
for i in ret: #然后两次循环这个变量
print(i)
for i in ret:
print(i)
return HttpResponse("ok")
输出结果:
#只查询了一次,但是打印了两次,说明第一次查询的值已经缓存到了变量中,下次直接从缓存中拿值就可以了
'''
(0.001) SELECT "app01_article"."id", "app01_article"."title", "app01_article"."desc", "app01_article"."read_count", "app01_article"."comment_count", "app01_article"."up_count", "app01_
article"."down_count", "app01_article"."create_time", "app01_article"."category_id", "app01_article"."user_id", "app01_article"."site_article_category_id" FROM "app01_article"; args=()
bootstrap导航栏.nav与.navbar区别
[Python]循环嵌套nested loop-练习题
Java提高十五:容器元素比较Comparable&Comparator深入分析
dsds
sql
dsdsds
dsds
东京不太热
dsds
东京有点热
射太阳的人
bootstrap导航栏.nav与.navbar区别
[Python]循环嵌套nested loop-练习题
Java提高十五:容器元素比较Comparable&Comparator深入分析
dsds
sql
dsdsds
dsds
东京不太热
dsds
东京有点热
射太阳的人
'''
优化查询
exists()与iterator()方法
exists:
简单的使用if语句进行判断也会完全执行整个queryset并且把数据放入cache,虽然你并不需要这些 数据!为了避免这个,可以用exists()方法来检查是否有数据:
if queryResult.exists():
#SELECT (1) AS "a" FROM "blog_article" LIMIT 1; args=()
print("exists...")
if queryResult.exists():
#SELECT (1) AS "a" FROM "blog_article" LIMIT 1; args=()
print("exists...")
iterator:
当queryset非常巨大时,cache会成为问题。
处理成千上万的记录时,将它们一次装入内存是很浪费的。更糟糕的是,巨大的queryset可能会锁住系统 进程,让你的程序濒临崩溃。要避免在遍历数据的同时产生queryset cache,可以使用iterator()方法 来获取数据,处理完数据就将其丢弃。
def queryTest(request):
ret=models.Article.objects.all().iterator() #优化查询后面添加iterator(),相当于是一个迭代器
#iterator()可以一次只从数据库获取少量数据,这样可以节省内存
for i in ret:
print(i)
for i in ret:
print(i) #第二次无结果
return HttpResponse("ok")
输出结果:
#优化查询就是迭代器第一次查询遍历到最后了,后面在打印一次就取得是空值
'''
(0.001) SELECT "app01_article"."id", "app01_article"."title", "app01_article"."desc", "app01_article"."read_count", "app01_article"."comment_count", "app01_article"."up_count", "app01_
article"."down_count", "app01_article"."create_time", "app01_article"."category_id", "app01_article"."user_id", "app01_article"."site_article_category_id" FROM "app01_article"; args=()
bootstrap导航栏.nav与.navbar区别
[Python]循环嵌套nested loop-练习题
Java提高十五:容器元素比较Comparable&Comparator深入分析
dsds
sql
dsdsds
dsds
东京不太热
dsds
东京有点热
射太阳的人
'''
x
def queryTest(request):
ret=models.Article.objects.all().iterator() #优化查询后面添加iterator(),相当于是一个迭代器
#iterator()可以一次只从数据库获取少量数据,这样可以节省内存
for i in ret:
print(i)
for i in ret:
print(i) #第二次无结果
return HttpResponse("ok")
输出结果:
#优化查询就是迭代器第一次查询遍历到最后了,后面在打印一次就取得是空值
'''
(0.001) SELECT "app01_article"."id", "app01_article"."title", "app01_article"."desc", "app01_article"."read_count", "app01_article"."comment_count", "app01_article"."up_count", "app01_
article"."down_count", "app01_article"."create_time", "app01_article"."category_id", "app01_article"."user_id", "app01_article"."site_article_category_id" FROM "app01_article"; args=()
bootstrap导航栏.nav与.navbar区别
[Python]循环嵌套nested loop-练习题
Java提高十五:容器元素比较Comparable&Comparator深入分析
dsds
sql
dsdsds
dsds
东京不太热
dsds
东京有点热
射太阳的人
'''
中介模型
处理类似搭配 pizza 和 topping 这样简单的多对多关系时,使用标准的ManyToManyField 就可以了。但是,有时你可能需要关联数据到两个模型之间的关系上。
例如,有这样一个应用,它记录音乐家所属的音乐小组。我们可以用一个ManyToManyField 表示小组和成员之间的多对多关系。但是,有时你可能想知道更多成员关系的细节,比如成员是何时加入小组的。
对于这些情况,Django 允许你指定一个中介模型来定义多对多关系。 你可以将其他字段放在中介模型里面。源模型的ManyToManyField 字段将使用through 参数指向中介模型。对于官网上的的音乐小组的例子,我写的blog系统的关系的代码如下:
class Article(models.Model):
'''
文章表
'''
title = models.CharField(max_length=50, verbose_name='文章标题')
desc = models.CharField(max_length=255, verbose_name='文章描述')
read_count = models.IntegerField(default=0)
comment_count = models.IntegerField(default=0)
up_count = models.IntegerField(default=0)
down_count = models.IntegerField(default=0)
create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
category = models.ForeignKey(verbose_name='文章类型', to='Category', null=True,blank=True)
user = models.ForeignKey(verbose_name='所属用户', to='Userinfo')
tags = models.ManyToManyField(
to="Tag",
through='Article2Tag', #自定义创建多对多的表
through_fields=('article', 'tag'),
)
site_article_category = models.ForeignKey("SiteArticleCategory", null=True)
def __str__(self):
return self.title
class Mate:
verbose_name_plural = "文章表"
class Tag(models.Model):
title = models.CharField(verbose_name='标签名称', max_length=32)
blog = models.ForeignKey(verbose_name='所属博客', to='Blog')
class Mate:
verbose_name_plural = "标签表"
def __str__(self):
return self.title
class Article2Tag(models.Model):
article = models.ForeignKey(verbose_name='文章', to="Article")
tag = models.ForeignKey(verbose_name='标签', to="Tag")
class Meta:
unique_together = [ #唯一
('article', 'tag'),
]
def __str__(self):
return self.tag
Article2Tag
x
1
class Article(models.Model):
2
'''
3
文章表
4
'''
5
6
title = models.CharField(max_length=50, verbose_name='文章标题')
7
desc = models.CharField(max_length=255, verbose_name='文章描述')
8
read_count = models.IntegerField(default=0)
9
comment_count = models.IntegerField(default=0)
10
up_count = models.IntegerField(default=0)
11
down_count = models.IntegerField(default=0)
12
create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
13
category = models.ForeignKey(verbose_name='文章类型', to='Category', null=True,blank=True)
14
user = models.ForeignKey(verbose_name='所属用户', to='Userinfo')
15
tags = models.ManyToManyField(
16
to="Tag",
17
through='Article2Tag', #自定义创建多对多的表
18
through_fields=('article', 'tag'),
19
)
20
site_article_category = models.ForeignKey("SiteArticleCategory", null=True)
21
22
def __str__(self):
23
return self.title
24
class Mate:
25
verbose_name_plural = "文章表"
26
27
28
29
class Tag(models.Model):
30
title = models.CharField(verbose_name='标签名称', max_length=32)
31
blog = models.ForeignKey(verbose_name='所属博客', to='Blog')
32
33
class Mate:
34
verbose_name_plural = "标签表"
35
def __str__(self):
36
return self.title
37
38
39
40
41
42
class Article2Tag(models.Model):
43
article = models.ForeignKey(verbose_name='文章', to="Article")
44
tag = models.ForeignKey(verbose_name='标签', to="Tag")
45
class Meta:
46
unique_together = [ #唯一
47
('article', 'tag'),
48
]
49
50
def __str__(self):
51
return self.tag
文章表
标签表
文章跟标签的相关联的表
**还可以添加别的字段
id
id
article_id
tag_id
标签分类
。。
如何这样创建了就与普通的多对多字段不同,你不能使用add、 create和赋值语句(比如,beatles.members = [...])来创建关系:
为什么不能这样做? 这是因为你不能只创建 Person和 Group之间的关联关系,你还要指定 Membership模型中所需要的所有信息;而简单的add、create 和赋值语句是做不到这一点的。所以它们不能在使用中介模型的多对多关系中使用。此时,唯一的办法就是创建中介模型的实例。
remove()方法被禁用也是出于同样的原因。但是clear() 方法却是可用的。它可以清空某个实例所有的多对多关系:
只能通过添加表记录的方式来进行添加了
示例:
models.Article2Tag.objects.create(article_id=1,tag_id=1,) #后面添加自定义字段的值就好了
自定义字段的值就好了
x
1
models.Article2Tag.objects.create(article_id=1,tag_id=1,) #后面添加自定义字段的值就好了
查询优化
表数据
class UserInfo(AbstractUser):
"""
用户信息
"""
nid = models.BigAutoField(primary_key=True)
nickname = models.CharField(verbose_name='昵称', max_length=32)
telephone = models.CharField(max_length=11, blank=True, null=True, unique=True, verbose_name='手机号码')
avatar = models.FileField(verbose_name='头像',upload_to = 'avatar/',default="/avatar/default.png")
create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
fans = models.ManyToManyField(verbose_name='粉丝们',
to='UserInfo',
through='UserFans',
related_name='f',
through_fields=('user', 'follower'))
def __str__(self):
return self.username
class UserFans(models.Model):
"""
互粉关系表
"""
nid = models.AutoField(primary_key=True)
user = models.ForeignKey(verbose_name='博主', to='UserInfo', to_field='nid', related_name='users')
follower = models.ForeignKey(verbose_name='粉丝', to='UserInfo', to_field='nid', related_name='followers')
class Blog(models.Model):
"""
博客信息
"""
nid = models.BigAutoField(primary_key=True)
title = models.CharField(verbose_name='个人博客标题', max_length=64)
site = models.CharField(verbose_name='个人博客后缀', max_length=32, unique=True)
theme = models.CharField(verbose_name='博客主题', max_length=32)
user = models.OneToOneField(to='UserInfo', to_field='nid')
def __str__(self):
return self.title
class Category(models.Model):
"""
博主个人文章分类表
"""
nid = models.AutoField(primary_key=True)
title = models.CharField(verbose_name='分类标题', max_length=32)
blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')
class Article(models.Model):
nid = models.BigAutoField(primary_key=True)
title = models.CharField(max_length=50, verbose_name='文章标题')
desc = models.CharField(max_length=255, verbose_name='文章描述')
read_count = models.IntegerField(default=0)
comment_count= models.IntegerField(default=0)
up_count = models.IntegerField(default=0)
down_count = models.IntegerField(default=0)
category = models.ForeignKey(verbose_name='文章类型', to='Category', to_field='nid', null=True)
create_time = models.DateField(verbose_name='创建时间')
blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')
tags = models.ManyToManyField(
to="Tag",
through='Article2Tag',
through_fields=('article', 'tag'),
)
class ArticleDetail(models.Model):
"""
文章详细表
"""
nid = models.AutoField(primary_key=True)
content = models.TextField(verbose_name='文章内容', )
article = models.OneToOneField(verbose_name='所属文章', to='Article', to_field='nid')
class Comment(models.Model):
"""
评论表
"""
nid = models.BigAutoField(primary_key=True)
article = models.ForeignKey(verbose_name='评论文章', to='Article', to_field='nid')
content = models.CharField(verbose_name='评论内容', max_length=255)
create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
parent_comment = models.ForeignKey('self', blank=True, null=True, verbose_name='父级评论')
user = models.ForeignKey(verbose_name='评论者', to='UserInfo', to_field='nid')
up_count = models.IntegerField(default=0)
def __str__(self):
return self.content
class ArticleUpDown(models.Model):
"""
点赞表
"""
nid = models.AutoField(primary_key=True)
user = models.ForeignKey('UserInfo', null=True)
article = models.ForeignKey("Article", null=True)
models.BooleanField(verbose_name='是否赞')
class CommentUp(models.Model):
"""
点赞表
"""
nid = models.AutoField(primary_key=True)
user = models.ForeignKey('UserInfo', null=True)
comment = models.ForeignKey("Comment", null=True)
class Tag(models.Model):
nid = models.AutoField(primary_key=True)
title = models.CharField(verbose_name='标签名称', max_length=32)
blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')
class Article2Tag(models.Model):
nid = models.AutoField(primary_key=True)
article = models.ForeignKey(verbose_name='文章', to="Article", to_field='nid')
tag = models.ForeignKey(verbose_name='标签', to="Tag", to_field='nid')
1
124
1
class UserInfo(AbstractUser):
2
"""
3
用户信息
4
"""
5
nid = models.BigAutoField(primary_key=True)
6
nickname = models.CharField(verbose_name='昵称', max_length=32)
7
telephone = models.CharField(max_length=11, blank=True, null=True, unique=True, verbose_name='手机号码')
8
avatar = models.FileField(verbose_name='头像',upload_to = 'avatar/',default="/avatar/default.png")
9
create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
10
11
fans = models.ManyToManyField(verbose_name='粉丝们',
12
to='UserInfo',
13
through='UserFans',
14
related_name='f',
15
through_fields=('user', 'follower'))
16
17
def __str__(self):
18
return self.username
19
20
class UserFans(models.Model):
21
"""
22
互粉关系表
23
"""
24
nid = models.AutoField(primary_key=True)
25
user = models.ForeignKey(verbose_name='博主', to='UserInfo', to_field='nid', related_name='users')
26
follower = models.ForeignKey(verbose_name='粉丝', to='UserInfo', to_field='nid', related_name='followers')
27
28
class Blog(models.Model):
29
30
"""
31
博客信息
32
"""
33
nid = models.BigAutoField(primary_key=True)
34
title = models.CharField(verbose_name='个人博客标题', max_length=64)
35
site = models.CharField(verbose_name='个人博客后缀', max_length=32, unique=True)
36
theme = models.CharField(verbose_name='博客主题', max_length=32)
37
user = models.OneToOneField(to='UserInfo', to_field='nid')
38
def __str__(self):
39
return self.title
40
41
class Category(models.Model):
42
"""
43
博主个人文章分类表
44
"""
45
nid = models.AutoField(primary_key=True)
46
title = models.CharField(verbose_name='分类标题', max_length=32)
47
48
blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')
49
50
class Article(models.Model):
51
52
nid = models.BigAutoField(primary_key=True)
53
title = models.CharField(max_length=50, verbose_name='文章标题')
54
desc = models.CharField(max_length=255, verbose_name='文章描述')
55
read_count = models.IntegerField(default=0)
56
comment_count= models.IntegerField(default=0)
57
up_count = models.IntegerField(default=0)
58
down_count = models.IntegerField(default=0)
59
category = models.ForeignKey(verbose_name='文章类型', to='Category', to_field='nid', null=True)
60
create_time = models.DateField(verbose_name='创建时间')
61
blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')
62
tags = models.ManyToManyField(
63
to="Tag",
64
through='Article2Tag',
65
through_fields=('article', 'tag'),
66
)
67
68
69
class ArticleDetail(models.Model):
70
"""
71
文章详细表
72
"""
73
nid = models.AutoField(primary_key=True)
74
content = models.TextField(verbose_name='文章内容', )
75
76
article = models.OneToOneField(verbose_name='所属文章', to='Article', to_field='nid')
77
78
79
class Comment(models.Model):
80
"""
81
评论表
82
"""
83
nid = models.BigAutoField(primary_key=True)
84
article = models.ForeignKey(verbose_name='评论文章', to='Article', to_field='nid')
85
content = models.CharField(verbose_name='评论内容', max_length=255)
86
create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
87
88
parent_comment = models.ForeignKey('self', blank=True, null=True, verbose_name='父级评论')
89
user = models.ForeignKey(verbose_name='评论者', to='UserInfo', to_field='nid')
90
91
up_count = models.IntegerField(default=0)
92
93
def __str__(self):
94
return self.content
95
96
class ArticleUpDown(models.Model):
97
"""
98
点赞表
99
"""
100
nid = models.AutoField(primary_key=True)
101
user = models.ForeignKey('UserInfo', null=True)
102
article = models.ForeignKey("Article", null=True)
103
models.BooleanField(verbose_name='是否赞')
104
105
class CommentUp(models.Model):
106
"""
107
点赞表
108
"""
109
nid = models.AutoField(primary_key=True)
110
user = models.ForeignKey('UserInfo', null=True)
111
comment = models.ForeignKey("Comment", null=True)
112
113
114
class Tag(models.Model):
115
nid = models.AutoField(primary_key=True)
116
title = models.CharField(verbose_name='标签名称', max_length=32)
117
blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')
118
119
120
121
class Article2Tag(models.Model):
122
nid = models.AutoField(primary_key=True)
123
article = models.ForeignKey(verbose_name='文章', to="Article", to_field='nid')
124
tag = models.ForeignKey(verbose_name='标签', to="Tag", to_field='nid')
select_related
简单使用
对于一对一字段(OneToOneField)和外键字段(ForeignKey),可以使用select_related 来对QuerySet进行优化。
select_related 返回一个QuerySet,当执行它的查询时它沿着外键关系查询关联的对象的数据。它会生成一个复杂的查询并引起性能的损耗,但是在以后使用外键关系时将不需要数据库查询。
简单说,在对QuerySet使用select_related()函数后,Django会获取相应外键对应的对象,从而在之后需要的时候不必再查询数据库了。
下面的例子解释了普通查询和select_related() 查询的区别。
普通查询
(0.000) SELECT "app01_category"."id", "app01_category"."title", "app01_category"."blog_id" FROM "app01_category" WHERE "app01_category"."id" = 2; args=(2,)
yang的python
x
1
2
(0.000) SELECT "app01_category"."id", "app01_category"."title", "app01_category"."blog_id" FROM "app01_category" WHERE "app01_category"."id" = 2; args=(2,)
3
yang的python
优化查询
如果我们使用select_related()函数:
articleList = models.Article.objects.select_related("category").all()
for article_obj in articleList:
# Doesn't hit the database, because article_obj.category
# has been prepopulated in the previous query.
print(article_obj.category)
输出结果:
#可以看到sql语句中,以最左查询 LEFT OUTER JOIN 以左表为主
'''
(0.002) SELECT "app01_article"."id", "app01_article"."title", "app01_article"."desc", "app01_article"."read_count", "app01_article"."comment_count", "app01_article"."up_count", "app01_
article"."down_count", "app01_article"."create_time", "app01_article"."category_id", "app01_article"."user_id", "app01_article"."site_article_category_id", "app01_category"."id", "app0
1_category"."title", "app01_category"."blog_id" FROM "app01_article" LEFT OUTER JOIN "app01_category" ON ("app01_article"."category_id" = "app01_category"."id"); args=()
yang的web
yang的python
yang的java
None
None
None
None
None
None
None
None
'''
x
22
1
articleList = models.Article.objects.select_related("category").all()
2
3
for article_obj in articleList:
4
# Doesn't hit the database, because article_obj.category
5
# has been prepopulated in the previous query.
6
print(article_obj.category)
7
8
9
10
输出结果:
11
#可以看到sql语句中,以最左查询 LEFT OUTER JOIN 以左表为主
12
'''
13
(0.002) SELECT "app01_article"."id", "app01_article"."title", "app01_article"."desc", "app01_article"."read_count", "app01_article"."comment_count", "app01_article"."up_count", "app01_
14
article"."down_count", "app01_article"."create_time", "app01_article"."category_id", "app01_article"."user_id", "app01_article"."site_article_category_id", "app01_category"."id", "app0
15
1_category"."title", "app01_category"."blog_id" FROM "app01_article" LEFT OUTER JOIN "app01_category" ON ("app01_article"."category_id" = "app01_category"."id"); args=()
16
yang的web
17
yang的python
18
yang的java
19
None
20
None
21
None
22
None
23
None
24
None
25
None
26
None
27
28
'''
总结
- select_related主要针一对一和多对一关系进行优化。
- select_related使用SQL的JOIN语句进行优化,通过减少SQL查询的次数来进行优化、提高性能。
- 可以通过可变长参数指定需要select_related的字段名。也可以通过使用双下划线“__”连接字段名来实现指定的递归查询。
- 没有指定的字段不会缓存,没有指定的深度不会缓存,如果要访问的话Django会再次进行SQL查询。
- 也可以通过depth参数指定递归的深度,Django会自动缓存指定深度内所有的字段。如果要访问指定深度外的字段,Django会再次进行SQL查询。
- 也接受无参数的调用,Django会尽可能深的递归查询所有的字段。但注意有Django递归的限制和性能的浪费。
- Django >= 1.7,链式调用的select_related相当于使用可变长参数。Django < 1.7,链式调用会导致前边的select_related失效,只保留最后一个。
处理类似搭配 pizza 和 topping 这样简单的多对多关系时,使用标准的ManyToManyField 就可以了。但是,有时你可能需要关联数据到两个模型之间的关系上。
例如,有这样一个应用,它记录音乐家所属的音乐小组。我们可以用一个ManyToManyField 表示小组和成员之间的多对多关系。但是,有时你可能想知道更多成员关系的细节,比如成员是何时加入小组的。
对于这些情况,Django 允许你指定一个中介模型来定义多对多关系。 你可以将其他字段放在中介模型里面。源模型的ManyToManyField 字段将使用through 参数指向中介模型。对于官网上的的音乐小组的例子,我写的blog系统的关系的代码如下:
class Article(models.Model):
'''
文章表
'''
title = models.CharField(max_length=50, verbose_name='文章标题')
desc = models.CharField(max_length=255, verbose_name='文章描述')
read_count = models.IntegerField(default=0)
comment_count = models.IntegerField(default=0)
up_count = models.IntegerField(default=0)
down_count = models.IntegerField(default=0)
create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
category = models.ForeignKey(verbose_name='文章类型', to='Category', null=True,blank=True)
user = models.ForeignKey(verbose_name='所属用户', to='Userinfo')
tags = models.ManyToManyField(
to="Tag",
through='Article2Tag', #自定义创建多对多的表
through_fields=('article', 'tag'),
)
site_article_category = models.ForeignKey("SiteArticleCategory", null=True)
def __str__(self):
return self.title
class Mate:
verbose_name_plural = "文章表"
class Tag(models.Model):
title = models.CharField(verbose_name='标签名称', max_length=32)
blog = models.ForeignKey(verbose_name='所属博客', to='Blog')
class Mate:
verbose_name_plural = "标签表"
def __str__(self):
return self.title
class Article2Tag(models.Model):
article = models.ForeignKey(verbose_name='文章', to="Article")
tag = models.ForeignKey(verbose_name='标签', to="Tag")
class Meta:
unique_together = [ #唯一
('article', 'tag'),
]
def __str__(self):
return self.tag
x
class Article(models.Model):
'''
文章表
'''
title = models.CharField(max_length=50, verbose_name='文章标题')
desc = models.CharField(max_length=255, verbose_name='文章描述')
read_count = models.IntegerField(default=0)
comment_count = models.IntegerField(default=0)
up_count = models.IntegerField(default=0)
down_count = models.IntegerField(default=0)
create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
category = models.ForeignKey(verbose_name='文章类型', to='Category', null=True,blank=True)
user = models.ForeignKey(verbose_name='所属用户', to='Userinfo')
tags = models.ManyToManyField(
to="Tag",
through='Article2Tag', #自定义创建多对多的表
through_fields=('article', 'tag'),
)
site_article_category = models.ForeignKey("SiteArticleCategory", null=True)
def __str__(self):
return self.title
class Mate:
verbose_name_plural = "文章表"
class Tag(models.Model):
title = models.CharField(verbose_name='标签名称', max_length=32)
blog = models.ForeignKey(verbose_name='所属博客', to='Blog')
class Mate:
verbose_name_plural = "标签表"
def __str__(self):
return self.title
class Article2Tag(models.Model):
article = models.ForeignKey(verbose_name='文章', to="Article")
tag = models.ForeignKey(verbose_name='标签', to="Tag")
class Meta:
unique_together = [ #唯一
('article', 'tag'),
]
def __str__(self):
return self.tag
文章表 |
标签表 | 文章跟标签的相关联的表 | **还可以添加别的字段 | ||||||
id | id | article_id | tag_id | 标签分类 | 。。 | ||||
如何这样创建了就与普通的多对多字段不同,你不能使用add、 create和赋值语句(比如,beatles.members = [...])来创建关系:
为什么不能这样做? 这是因为你不能只创建 Person和 Group之间的关联关系,你还要指定 Membership模型中所需要的所有信息;而简单的add、create 和赋值语句是做不到这一点的。所以它们不能在使用中介模型的多对多关系中使用。此时,唯一的办法就是创建中介模型的实例。
remove()方法被禁用也是出于同样的原因。但是clear() 方法却是可用的。它可以清空某个实例所有的多对多关系:
只能通过添加表记录的方式来进行添加了
示例:
models.Article2Tag.objects.create(article_id=1,tag_id=1,) #后面添加自定义字段的值就好了
x
models.Article2Tag.objects.create(article_id=1,tag_id=1,) #后面添加自定义字段的值就好了
查询优化
表数据
class UserInfo(AbstractUser):
"""
用户信息
"""
nid = models.BigAutoField(primary_key=True)
nickname = models.CharField(verbose_name='昵称', max_length=32)
telephone = models.CharField(max_length=11, blank=True, null=True, unique=True, verbose_name='手机号码')
avatar = models.FileField(verbose_name='头像',upload_to = 'avatar/',default="/avatar/default.png")
create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
fans = models.ManyToManyField(verbose_name='粉丝们',
to='UserInfo',
through='UserFans',
related_name='f',
through_fields=('user', 'follower'))
def __str__(self):
return self.username
class UserFans(models.Model):
"""
互粉关系表
"""
nid = models.AutoField(primary_key=True)
user = models.ForeignKey(verbose_name='博主', to='UserInfo', to_field='nid', related_name='users')
follower = models.ForeignKey(verbose_name='粉丝', to='UserInfo', to_field='nid', related_name='followers')
class Blog(models.Model):
"""
博客信息
"""
nid = models.BigAutoField(primary_key=True)
title = models.CharField(verbose_name='个人博客标题', max_length=64)
site = models.CharField(verbose_name='个人博客后缀', max_length=32, unique=True)
theme = models.CharField(verbose_name='博客主题', max_length=32)
user = models.OneToOneField(to='UserInfo', to_field='nid')
def __str__(self):
return self.title
class Category(models.Model):
"""
博主个人文章分类表
"""
nid = models.AutoField(primary_key=True)
title = models.CharField(verbose_name='分类标题', max_length=32)
blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')
class Article(models.Model):
nid = models.BigAutoField(primary_key=True)
title = models.CharField(max_length=50, verbose_name='文章标题')
desc = models.CharField(max_length=255, verbose_name='文章描述')
read_count = models.IntegerField(default=0)
comment_count= models.IntegerField(default=0)
up_count = models.IntegerField(default=0)
down_count = models.IntegerField(default=0)
category = models.ForeignKey(verbose_name='文章类型', to='Category', to_field='nid', null=True)
create_time = models.DateField(verbose_name='创建时间')
blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')
tags = models.ManyToManyField(
to="Tag",
through='Article2Tag',
through_fields=('article', 'tag'),
)
class ArticleDetail(models.Model):
"""
文章详细表
"""
nid = models.AutoField(primary_key=True)
content = models.TextField(verbose_name='文章内容', )
article = models.OneToOneField(verbose_name='所属文章', to='Article', to_field='nid')
class Comment(models.Model):
"""
评论表
"""
nid = models.BigAutoField(primary_key=True)
article = models.ForeignKey(verbose_name='评论文章', to='Article', to_field='nid')
content = models.CharField(verbose_name='评论内容', max_length=255)
create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
parent_comment = models.ForeignKey('self', blank=True, null=True, verbose_name='父级评论')
user = models.ForeignKey(verbose_name='评论者', to='UserInfo', to_field='nid')
up_count = models.IntegerField(default=0)
def __str__(self):
return self.content
class ArticleUpDown(models.Model):
"""
点赞表
"""
nid = models.AutoField(primary_key=True)
user = models.ForeignKey('UserInfo', null=True)
article = models.ForeignKey("Article", null=True)
models.BooleanField(verbose_name='是否赞')
class CommentUp(models.Model):
"""
点赞表
"""
nid = models.AutoField(primary_key=True)
user = models.ForeignKey('UserInfo', null=True)
comment = models.ForeignKey("Comment", null=True)
class Tag(models.Model):
nid = models.AutoField(primary_key=True)
title = models.CharField(verbose_name='标签名称', max_length=32)
blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')
class Article2Tag(models.Model):
nid = models.AutoField(primary_key=True)
article = models.ForeignKey(verbose_name='文章', to="Article", to_field='nid')
tag = models.ForeignKey(verbose_name='标签', to="Tag", to_field='nid')
class UserInfo(AbstractUser):
"""
用户信息
"""
nid = models.BigAutoField(primary_key=True)
nickname = models.CharField(verbose_name='昵称', max_length=32)
telephone = models.CharField(max_length=11, blank=True, null=True, unique=True, verbose_name='手机号码')
avatar = models.FileField(verbose_name='头像',upload_to = 'avatar/',default="/avatar/default.png")
create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
fans = models.ManyToManyField(verbose_name='粉丝们',
to='UserInfo',
through='UserFans',
related_name='f',
through_fields=('user', 'follower'))
def __str__(self):
return self.username
class UserFans(models.Model):
"""
互粉关系表
"""
nid = models.AutoField(primary_key=True)
user = models.ForeignKey(verbose_name='博主', to='UserInfo', to_field='nid', related_name='users')
follower = models.ForeignKey(verbose_name='粉丝', to='UserInfo', to_field='nid', related_name='followers')
class Blog(models.Model):
"""
博客信息
"""
nid = models.BigAutoField(primary_key=True)
title = models.CharField(verbose_name='个人博客标题', max_length=64)
site = models.CharField(verbose_name='个人博客后缀', max_length=32, unique=True)
theme = models.CharField(verbose_name='博客主题', max_length=32)
user = models.OneToOneField(to='UserInfo', to_field='nid')
def __str__(self):
return self.title
class Category(models.Model):
"""
博主个人文章分类表
"""
nid = models.AutoField(primary_key=True)
title = models.CharField(verbose_name='分类标题', max_length=32)
blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')
class Article(models.Model):
nid = models.BigAutoField(primary_key=True)
title = models.CharField(max_length=50, verbose_name='文章标题')
desc = models.CharField(max_length=255, verbose_name='文章描述')
read_count = models.IntegerField(default=0)
comment_count= models.IntegerField(default=0)
up_count = models.IntegerField(default=0)
down_count = models.IntegerField(default=0)
category = models.ForeignKey(verbose_name='文章类型', to='Category', to_field='nid', null=True)
create_time = models.DateField(verbose_name='创建时间')
blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')
tags = models.ManyToManyField(
to="Tag",
through='Article2Tag',
through_fields=('article', 'tag'),
)
class ArticleDetail(models.Model):
"""
文章详细表
"""
nid = models.AutoField(primary_key=True)
content = models.TextField(verbose_name='文章内容', )
article = models.OneToOneField(verbose_name='所属文章', to='Article', to_field='nid')
class Comment(models.Model):
"""
评论表
"""
nid = models.BigAutoField(primary_key=True)
article = models.ForeignKey(verbose_name='评论文章', to='Article', to_field='nid')
content = models.CharField(verbose_name='评论内容', max_length=255)
create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
parent_comment = models.ForeignKey('self', blank=True, null=True, verbose_name='父级评论')
user = models.ForeignKey(verbose_name='评论者', to='UserInfo', to_field='nid')
up_count = models.IntegerField(default=0)
def __str__(self):
return self.content
class ArticleUpDown(models.Model):
"""
点赞表
"""
nid = models.AutoField(primary_key=True)
user = models.ForeignKey('UserInfo', null=True)
article = models.ForeignKey("Article", null=True)
models.BooleanField(verbose_name='是否赞')
class CommentUp(models.Model):
"""
点赞表
"""
nid = models.AutoField(primary_key=True)
user = models.ForeignKey('UserInfo', null=True)
comment = models.ForeignKey("Comment", null=True)
class Tag(models.Model):
nid = models.AutoField(primary_key=True)
title = models.CharField(verbose_name='标签名称', max_length=32)
blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')
class Article2Tag(models.Model):
nid = models.AutoField(primary_key=True)
article = models.ForeignKey(verbose_name='文章', to="Article", to_field='nid')
tag = models.ForeignKey(verbose_name='标签', to="Tag", to_field='nid')
select_related
对于一对一字段(OneToOneField)和外键字段(ForeignKey),可以使用select_related 来对QuerySet进行优化。
select_related 返回一个QuerySet,当执行它的查询时它沿着外键关系查询关联的对象的数据。它会生成一个复杂的查询并引起性能的损耗,但是在以后使用外键关系时将不需要数据库查询。
简单说,在对QuerySet使用select_related()函数后,Django会获取相应外键对应的对象,从而在之后需要的时候不必再查询数据库了。
下面的例子解释了普通查询和select_related() 查询的区别。
普通查询
(0.000) SELECT "app01_category"."id", "app01_category"."title", "app01_category"."blog_id" FROM "app01_category" WHERE "app01_category"."id" = 2; args=(2,)
yang的python
x
(0.000) SELECT "app01_category"."id", "app01_category"."title", "app01_category"."blog_id" FROM "app01_category" WHERE "app01_category"."id" = 2; args=(2,)
yang的python
articleList = models.Article.objects.select_related("category").all()
for article_obj in articleList:
# Doesn't hit the database, because article_obj.category
# has been prepopulated in the previous query.
print(article_obj.category)
输出结果:
#可以看到sql语句中,以最左查询 LEFT OUTER JOIN 以左表为主
'''
(0.002) SELECT "app01_article"."id", "app01_article"."title", "app01_article"."desc", "app01_article"."read_count", "app01_article"."comment_count", "app01_article"."up_count", "app01_
article"."down_count", "app01_article"."create_time", "app01_article"."category_id", "app01_article"."user_id", "app01_article"."site_article_category_id", "app01_category"."id", "app0
1_category"."title", "app01_category"."blog_id" FROM "app01_article" LEFT OUTER JOIN "app01_category" ON ("app01_article"."category_id" = "app01_category"."id"); args=()
yang的web
yang的python
yang的java
None
None
None
None
None
None
None
None
'''
x
articleList = models.Article.objects.select_related("category").all()
for article_obj in articleList:
# Doesn't hit the database, because article_obj.category
# has been prepopulated in the previous query.
print(article_obj.category)
输出结果:
#可以看到sql语句中,以最左查询 LEFT OUTER JOIN 以左表为主
'''
(0.002) SELECT "app01_article"."id", "app01_article"."title", "app01_article"."desc", "app01_article"."read_count", "app01_article"."comment_count", "app01_article"."up_count", "app01_
article"."down_count", "app01_article"."create_time", "app01_article"."category_id", "app01_article"."user_id", "app01_article"."site_article_category_id", "app01_category"."id", "app0
1_category"."title", "app01_category"."blog_id" FROM "app01_article" LEFT OUTER JOIN "app01_category" ON ("app01_article"."category_id" = "app01_category"."id"); args=()
yang的web
yang的python
yang的java
None
None
None
None
None
None
None
None
'''
- select_related主要针一对一和多对一关系进行优化。
- select_related使用SQL的JOIN语句进行优化,通过减少SQL查询的次数来进行优化、提高性能。
- 可以通过可变长参数指定需要select_related的字段名。也可以通过使用双下划线“__”连接字段名来实现指定的递归查询。
- 没有指定的字段不会缓存,没有指定的深度不会缓存,如果要访问的话Django会再次进行SQL查询。
- 也可以通过depth参数指定递归的深度,Django会自动缓存指定深度内所有的字段。如果要访问指定深度外的字段,Django会再次进行SQL查询。
- 也接受无参数的调用,Django会尽可能深的递归查询所有的字段。但注意有Django递归的限制和性能的浪费。
- Django >= 1.7,链式调用的select_related相当于使用可变长参数。Django < 1.7,链式调用会导致前边的select_related失效,只保留最后一个。