我的选择查询+序列化功能需要很长时间才能完成(〜30s,数据库中有15k +行)。有没有人对我如何优化或对我做错的事情有见解?非常感谢!
模式:
查询
query = Post.select().objects()
data = [p.serialize() for p in query.iterator()]
return json.dumps(data)
Function(类发布)
def serialize(self):
authors = [{'name': post_authors.author.name} for post_authors in self.authors]
tags = [{'name': post_tags.tag.name} for post_tags in self.tags]
return {
'name': self.name,
'authors': authors,
'tags': tags
}
我尝试在后向引用上使用model_to_dict
,但发现它花了更长的时间。
您对序列化的每个帖子都进行两个额外的查询(一个用于获取标签,一个用于获取作者)。您应该尝试使用fn.GROUP_CONCAT
或类似名称来加入和汇总这些标签/作者名称。然后,您可以将所有内容放入一个(可能更快)的查询中。
此处的一般提示:http://docs.peewee-orm.com/en/latest/peewee/relationships.html#avoiding-the-n-1-problem