我正在使用 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)
最佳答案
90 毫秒对于针对本地数据库执行的查询来说仍然相当多,所以我猜有很多连接。
这种情况下的一般规则是通过以下方式减少 ORM 的使用:
- 仅选择必填字段或推迟不需要且成本高昂的字段 查找 - 看 https://docs.djangoproject.com/en/dev/ref/models/querysets/#defer和 https://docs.djangoproject.com/en/dev/ref/models/querysets/#only
- 如果您只显示字段的确切值,请在查询集上使用
values()
或values_list()
,这将阻止 Django ORM 构建所有对象并执行相关信号
可能获得显着 yield 的最快方法是使用 johnny-cache http://packages.python.org/johnny-cache/ 缓存 QuerySets。或使用 {% cache ... %}
关于mysql - Django 查询速度快,渲染速度慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12870302/