2012-10-13 134 views
2

我正在用Django和MySQL运行一个网站,我试图优化它。 为此,我使用django调试工具栏,并特别关注SQL部分,我认为这是我的页面负载很长的原因。Django快速查询,但渲染速度慢

当我查看django调试工具栏中的SQL部分时,它说我的查询总共需要大约90ms。 但是,如果我把一个计时器周围的python渲染功能,然后它需要超过3秒(这是更接近我实际看到时,重新加载页面)...

如何查询是快速相比渲染?

编辑:这里是模板的代码简化到最大:

<div id="content_annonces" class="ui-widget ui-corner-all"> 
    <table> 
     {% if latest_annonces_list %} 
      here goes the content 
     {% else %} 
      nothing found 
     {% endif %} 
    </table> 
</div> 

,你可以看到,那被认为是昂贵的代码的唯一和平是调用该对象时所要求的SQL查询latest_annonces_list。 但是,当我使用Django调试工具栏配置它,它说,这个查询所经过的90毫秒,而呈现大约需要3秒......

而且这里去的latest_annonces_list内容:

result = Annonce.objects.select_related('vehicule', 'vehicule__marque') 
     .filter(vehicule__marque__in=self.marques).order_by('prix')[:10] 

模型在这里:

class Marque(models.Model): 
    name = models.CharField(db_index=True, primary_key=True, max_length=100) 

class Vehicule(models.Model): 
    modele  = models.CharField(primary_key=True, db_index=True, max_length=100) 
    gen_modele = models.CharField(db_index=True, max_length=100) 
    marque  = models.ForeignKey(Marque) 
    categories = models.ManyToManyField(Categorie) 
    click  = models.PositiveIntegerField(default=0) 

class Annonce(models.Model): 
    vehicule  = models.ForeignKey(Vehicule, db_index=True) 
    porte   = models.ForeignKey(Porte, db_index=True) 
    carburant  = models.ForeignKey(Carburant, db_index=True) 
    bv   = models.ForeignKey(Boite, db_index=True) 
    prix   = models.DecimalField(db_index=True,max_digits=8, decimal_places=2) 
    km   = models.PositiveIntegerField(db_index=True) 
    dpt   = models.CharField(db_index=True, max_length=50) 
    annonceur  = models.ForeignKey(Annonceur, db_index=True) 
    img   = models.URLField() 
    url   = models.URLField(max_length=2000) 
    finition  = models.CharField(max_length=500) 
    cylindree  = models.CharField(max_length=500) 
    moteur  = models.CharField(max_length=500) 
    annee   = models.DateTimeField(u'annee vehicule', db_index=True) 
    pub_date  = models.DateTimeField(u'date publication') 
    last_touched = models.DateTimeField(u'derniere modification') 
    last_scan  = models.DateTimeField(u'dernier scan') 
    type_ann  = models.ForeignKey(Type_Annonce, db_index=True) 
    type_vendeur = models.ForeignKey(Vendeu 

R,db_index = TRUE)

+0

船长在这里明显的最快方法 - 也许你有低效的代码在你的渲染逻辑? – Rogach

+0

嗯,我想到了它,但在模板中可能是低效的唯一的事情是查询相关...其余的只是由字符串组成...... – EagleOne

+0

好吧,我只是在开玩笑。问题是我们无法看到代码就说这个问题。你能提供一个你的问题的小例子吗? – Rogach

回答

1

90毫秒仍然是相当多的针对本地数据库执行的查询,所以我想有很多连接。

在这种情况下一般规律是减少由ORM用法:

大概有显著增益要么使用约翰尼缓存http://packages.python.org/johnny-cache/缓存查询集或缓存输出使用{% cache ... %}

+0

谢谢,这实际上是我做的。我尝试了两件事:使用nonrel数据库(mongodB),但迁移工作太多。第二件事是摆脱ORM的使用(它太多了)。尽管如此,我会尝试使用values和values_list。在我看来这很有趣。然而,我仍然不明白为什么我在查询执行和渲染耗用时间之间有这样的差异。哦,关于缓存,我已经使用它,但我想提高侧面的性能。 – EagleOne

相关问题