优化多对多表上的Peewee Select查询

问题描述 投票:0回答:1

我的选择查询+序列化功能需要很长时间才能完成(〜30s,数据库中有15k +行)。有没有人对我如何优化或对我做错的事情有见解?非常感谢!

模式

  • 邮政:身份证,姓名
  • [Post_Tags:post_id(backref =“ tags”),tag_id
  • 标签:ID,名称
  • [Post_Authors:post_id(backref =“ authors”),author_id
  • 作者:ID,名称

查询

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,但发现它花了更长的时间。

postgresql peewee
1个回答
0
投票

您对序列化的每个帖子都进行两个额外的查询(一个用于获取标签,一个用于获取作者)。您应该尝试使用fn.GROUP_CONCAT或类似名称来加入和汇总这些标签/作者名称。然后,您可以将所有内容放入一个(可能更快)的查询中。

此处的一般提示:http://docs.peewee-orm.com/en/latest/peewee/relationships.html#avoiding-the-n-1-problem

© www.soinside.com 2019 - 2024. All rights reserved.