在sqlalchemy中有效地访问集合

时间:2015-06-12 07:19:55

标签: python sqlalchemy flask-sqlalchemy

我对sqlalchemy和SQL一般都很新。我有以下型号

class User(Base):
    """Stores users and their magazines"""
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    magazines = relationship('Magazine', secondary=magazine_association)

class Magazine(Base):
    """Stores magazines and their articles"""
    __tablename__ = 'magazine'
    id = Column(Integer,primary_key = True)
    articles = relationship('Article',cascade="save-update, merge, delete",backref='magazine',lazy='dynamic')

class Article(Base):
    """Stores article information"""
    __tablename__ = 'article'
    id = Column(Integer, primary_key = True)
    title = Column(String(240), default='Unknown Title')
    category = Column(String(40), default='Unknown category')
    rank = Column(Integer, default=0)
    #Backrefs
    magazine_id = Column(Integer,ForeignKey('magazine.id'))

magazine_association = Table('magazine_association', Base.metadata,
    Column('magazine_id',Integer,ForeignKey('magazine.id', ondelete='cascade')),
    Column('user_id',Integer,ForeignKey('user.id', ondelete= 'cascade'))
)

我正在尝试访问特定用户的所有文章。我可以遍历所有杂志并获取用户拥有的每本杂志的所有文章,如下所示

for mag in user.magazines:
    for art in mag.articles:
        return art.title

如果文章和杂志的数量非常大,使用限制和偏移分页的最佳方法是什么?我在创建单个查询时遇到问题,该查询可以为我提供可以分页的用户的文章集合。我需要这样做,因为我试图将其公开为REST API。

感谢任何指针。感谢

1 个答案:

答案 0 :(得分:0)

Flask-SQLAlchemy已经建立了分页支持。请参阅here