Skip to main content
 首页 » 编程设计

python之我如何在 Django View 中优化我的数据库查询集

2024年08月28日29mayingbao

我写了一个小的博客脚本作为 django 应用程序。我认为在单篇文章 View 中我有很多请求。但我不知道如何减少它们。

我通过一次查询获得所有博客文章。结果我得到了一个查询集。有了这个,我做了更多的 Action 。但对于每一个 Action ,django 调试器工具栏告诉我,它会一次又一次地访问数据库。

这是 View :

def single(request, slug): 
    articles = Article.objects.all() 
 
    article = articles.filter(slug=slug)[0] 
 
    newer_article = list(articles.filter(release_date__gt=article.release_date))[-1:] 
    older_article = articles.filter(release_date__lt=article.release_date)[:1] 
 
    return render_to_response( 
        'article/single%s.html' % extend, 
        locals(), 
        RequestContext(request) 
    ) 
  • 第一次点击我得到当前文章。
  • 第二次和第三次命中是获取前后文章

是否有一种解决方案可以仅在一次数据库命中时获得相同的结果?

结果:

只有 1 个查询的新版本。

def single(request, slug): 
    articles = list(Article.objects.all()) 
 
    for i, a in enumerate(articles): 
        if a.slug == slug: 
            article = a 
 
            if (i-1) >= 0: 
                newer_article = articles[i-1] 
            else: 
                newer_article = None 
 
            if (i+1) < len(articles): 
                older_article = articles[i+1] 
            else: 
                older_article = None 
 
            break 
 
    return render_to_response( 
        'article/single%s.html' % extend, 
        locals(), 
        RequestContext(request) 
    ) 

请您参考如下方法:

您可以像这样将其缩减为一个查询:

articles = list(Article.objects.order_by('release_date')) 
 
for index, art in enumerate(articles): 
    if art.slug == slug: 
        article = art 
        newer_article = articles[index+1] 
        older_article = articles[index-1] 
        break