标签:注意 request 不用 rom 返回 port 提高 sele name
articles = Article.objects.all()
print(articles)
from django.http import HttpResponse
from .models import Article, Category
def index(request):
# 使用select_related()方法提取相关联的数据表中的数据,会暂时的存放在内存中,
# 再次查看的时候就不用再次访问数据库表了,可以大大提高访问的效率
articles = Article.objects.select_related('category')
for article in articles:
print(article.category.name)
print(connection.queries)
return HttpResponse("success!")
最新文章
最新文章
最热文章
高评分文章
[{‘sql‘: ‘SELECT @@SQL_AUTO_IS_NULL‘, ‘time‘: ‘0.000‘}, {‘sql‘: ‘SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED‘, ‘time‘: ‘0.000‘}, {‘sql‘: ‘SELECT article.id, article.title, article.content, article.category_id, article.create_time, category.id, category.name, category.rating FROM article LEFT OUTER JOIN category ON (article.category_id = category.id)‘, ‘time‘: ‘0.000‘}]
from django.http import HttpResponse
from .models import Article, Category
def index(request):
articles = Article.objects.all()
for article in articles:
print(article.category.name)
print(connection.queries)
return HttpResponse("success!")
最新文章
最热文章
高评分文章
最新文章
[{‘sql‘: ‘SELECT @@SQL_AUTO_IS_NULL‘, ‘time‘: ‘0.000‘}, {‘sql‘: ‘SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED‘, ‘time‘: ‘0.000‘}, {‘sql‘: ‘SELECT article.id, article.title, article.content, article.category_id, article.create_time FROM article‘, ‘time‘: ‘0.000‘}, {‘sql‘: ‘SELECT category.id, category.name, category.rating FROM category WHERE category.id = 1 LIMIT 21‘, ‘time‘: ‘0.000‘}, {‘sql‘: ‘SELECT category.id, category.name, category.rating FROM category WHERE category.id = 2 LIMIT 21‘, ‘time‘: ‘0.000‘}, {‘sql‘: ‘SELECT category.id, category.name, category.rating FROM category WHERE category.id = 3 LIMIT 21‘, ‘time‘: ‘0.000‘}, {‘sql‘: ‘SELECT category.id, category.name, category.rating FROM category WHERE category.id = 1 LIMIT 21‘, ‘time‘: ‘0.000‘}]
注意:这个方法只能用在定义了外键的字段上,也可以说是用在外键的关联对象(表)上,对于多对多,或者是多对一的情况,不能使用select_related()方法。而应该使用“prefetch_related”来实现。
82.常用的返回QuerySet对象的方法使用详解:all,select_related
标签:注意 request 不用 rom 返回 port 提高 sele name
原文地址:https://www.cnblogs.com/guyan-2020/p/12268467.html