【发布时间】:2017-08-13 14:57:35
【问题描述】:
在我的 Pyramid 应用程序中,我有 models.py:
db = scoped_session(sessionmaker())
Base = declarative_base()
followers = Table('followers',
Base.metadata,
Column('follower_id', Integer, ForeignKey('artist.id')),
Column('followed_id', Integer, ForeignKey('artist.id')))
class Artist(Base):
__tablename__ = 'artist'
id = Column(Integer, primary_key=True)
title = Column(Text)
followed = relationship('Artist',
secondary=followers,
primaryjoin=(followers.c.follower_id == id),
secondaryjoin=(followers.c.followed_id == id),
backref=backref('followers', lazy='dynamic'),
lazy='dynamic')
Index('my_index', Artist.id, unique=True, mysql_length=255)
我的artist 表有 85,632 行,followers 辅助表有 420,749 行。
目前,如果我尝试像这样检索一些artist 中的followed:
db.query(Artist).first().folowed.all()
查询需要大约 30-40 毫秒来检索行,我该如何改进我的模型以减少这个时间?
顺便说一下,我的Artist 模型是基于这个tutorial。
【问题讨论】:
-
尝试使用 InnoDB,这样 ForeignKeys 由数据库处理,而不是由 SQLAlchemy。
-
我将
__table_args__ = {'mysql_engine': 'InnoDB'}添加到我的class Artist模型中。我必须升级我的数据库吗? -
尝试在
followers.follower_id上添加索引。 -
我添加了两个建议,每个查询的时间减少到 2 毫秒左右,谢谢!
标签: python database performance sqlalchemy pyramid