extra
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")) ''' 输出结果:'''
date_list=models.Article.objects.filter(user=user_obj).extra(select={ "fdate":"strftime('%%Y/%%m/%%d',create_time)"}).values_list("fdate").annotate(Count("id"))
'''
输出结果:
'''
参数之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'])
QuerySet
可切片
>>> 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_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深入分析dsdssqldsdsdsdsds东京不太热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深入分析dsdssqldsdsdsdsds东京不太热dsds东京有点热射太阳的人bootstrap导航栏.nav与.navbar区别[Python]循环嵌套nested loop-练习题Java提高十五:容器元素比较Comparable&Comparator深入分析dsdssqldsdsdsdsds东京不太热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深入分析dsdssqldsdsdsdsds东京不太热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
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 | 标签分类 | 。。 | ||||
为什么不能这样做? 这是因为你不能只创建 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", "app01_category"."title", "app01_category"."blog_id" FROM "app01_article" LEFT OUTER JOIN "app01_category" ON ("app01_article"."category_id" = "app01_category"."id"); args=()yang的webyang的pythonyang的javaNoneNoneNoneNoneNoneNoneNoneNone'''
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失效,只保留最后一个。