我正在运行一个有Django和MySQL的网站,我正在尝试优化它。 为此我使用django调试工具栏,我特别注意SQL部分,我认为,这是我的页面加载时间长的原因。
当我查看django调试工具栏中的SQL部分时,它说我的查询总共需要大约90毫秒。 但是如果我在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>
正如您所看到的,唯一可能代价高昂的代码是调用对象latest_annonces_list时请求的SQL查询。 但是当我使用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 :(得分:1)
90ms仍然是针对本地数据库执行的查询,所以我猜有很多连接。
在这种情况下的一般规则是通过以下方式减少ORM的使用:
values()
或values_list()
,这将阻止Django ORM构建所有对象并执行相关信号获得显着收益的最快方法可能是使用johnny-cache http://packages.python.org/johnny-cache/缓存QuerySet或使用{% cache ... %}
缓存输出