注意我是一个django noob并且还没有完全包围我的模型.Manager和model.query.querySet所以如果这个设置看起来很尴尬….
目前,页面加载查询集大约需要18秒,目前只有大约500条记录.每天平均会有大约100条新记录.
该数据库是Postgresql
慢视图:
def approvals(request): ... approved_submissions = QuestSubmission.objects.all_approved() ...
慢查询集:
class QuestSubmissionquerySet(models.query.querySet): ... def approved(self): return self.filter(is_approved=True) def completed(self): return self.filter(is_completed=True).order_by('-time_completed') ...class QuestSubmissionManager(models.Manager): def get_queryset(self): return QuestSubmissionquerySet(self.model,using=self._db) def all_approved(self,user=None): return self.get_queryset().approved().completed() ...
从QuestSubmission.objects.all_approved()得到的sql:
'SELECT "quest_manager_questsubmission"."ID","quest_manager_questsubmission"."quest_ID","quest_manager_questsubmission"."user_ID","quest_manager_questsubmission"."ordinal","quest_manager_questsubmission"."is_completed","quest_manager_questsubmission"."time_completed","quest_manager_questsubmission"."is_approved","quest_manager_questsubmission"."time_approved","quest_manager_questsubmission"."timestamp","quest_manager_questsubmission"."updated","quest_manager_questsubmission"."game_lab_transfer" FROM "quest_manager_questsubmission" WHERE ("quest_manager_questsubmission"."is_approved" = True AND "quest_manager_questsubmission"."is_completed" = True) ORDER BY "quest_manager_questsubmission"."time_completed" DESC'
缓慢的模型:
class QuestSubmission(models.Model): quest = models.ForeignKey(Quest) user = models.ForeignKey(settings.AUTH_USER_MODEL,related_name="quest_submission_user") ordinal = models.PositiveIntegerFIEld(default = 1,help_text = 'indicating submissions beyond the first for repeatable quests') is_completed = models.BooleanFIEld(default=False) time_completed = models.DateTimeFIEld(null=True,blank=True) is_approved = models.BooleanFIEld(default=False) time_approved = models.DateTimeFIEld(null=True,blank=True) timestamp = models.DateTimeFIEld(auto_Now=True,auto_Now_add=False) updated = models.DateTimeFIEld(auto_Now=False,auto_Now_add=True) game_lab_transfer = models.BooleanFIEld(default = False,help_text = 'XP not counted') class Meta: ordering = ["time_approved","time_completed"] objects = QuestSubmissionManager() #other methods ....
有哪些策略可以解决这个问题?我尝试使用django的Paginator,但它似乎只显示在页面中,但它仍然加载整个查询集.
解决方法 首先要看的是:>此查询是否因为返回非常大的结果集而变慢?
要么
>这个查询是否很慢,因为它需要一段时间才能过滤掉表格?
假设前者,除了“返回更少的数据”之外,你没有很多好的选择.
如果是后者,你可能应该在数据库上运行一个EXPLAIN,但是我会说你可能想要一个索引,可能是(is_approved,is_completed).可以通过以下方式完成:
class Meta: index_together = [ ["is_completed","is_approved"],]总结
以上是内存溢出为你收集整理的python – 从一个庞大且不断增长的数据集中优化慢速django查询集全部内容,希望文章能够帮你解决python – 从一个庞大且不断增长的数据集中优化慢速django查询集所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)