扩展WindowedRangeQuery以实现双向多对多关系

时间:2019-06-11 18:20:36

标签: python postgresql sqlalchemy

我正在尝试使用Flask为我的其余API构建实现分页方法。我想避免使用依赖于OFFSET和LIMIT的方法,并且发现了一个很棒的sqlalchemy示例here,使用Postgresql的window函数作为可靠的替代方法

该实现效果很好,但我想对其进行调整以从多对多选择中进行选择,而不仅仅是一个表。

主要部分是这样:

q = s.query(Playlist)

q.session.query(
       Playlist.id,
       func.row_number().over(order_by=Playlist.id).label('rownum'),
).from_self(Playlist.id)

,它将生成以下SQL:

SELECT anon_1.screens_id AS anon_1_screens_id 
FROM (SELECT screens.id AS screens_id, row_number() OVER (ORDER BY screens.id) AS rownum 
FROM screens) AS anon_1 

我需要更改FROM screens部分。最后,我希望使用以下SQL:

SELECT anon_1.screen_id, 
FROM (SELECT screens.id as screen_id, row_number() OVER (ORDER BY screens.id) AS rownum
FROM users_screens, users, screens WHERE screens.id = users_screens.screen_id AND users.id = users_screens.user_id AND users.id = 'some_user_id'
)AS anon_1 

如果需要,我的模型及其之间的关系为:


users_screens_association = Table('users_screens', Base.metadata,
    Column('user_id', Integer, ForeignKey('users.id')),
    Column('screen_id', Integer, ForeignKey('screens.id'))
)

class User(UserMixin, Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    # other columns are also defined

    screens = relationship('Screen',
                           secondary=users_screens_association,
                           back_populates='users',
                           lazy='dynamic')

class Screen(Base):
    __tablename__ = 'screens'

    id = Column(Integer, primary_key=True)
    # other columns are also defined

    users = relationship('User',
                         secondary=users_screens_association,
                         back_populates='screens')
)

对我来说理想的情况是:

  1. 根据用户ID从屏幕中选择一些相关行

    • table_filter = Screen.users.any(id='some_user_id')
  2. 可以在上一个选择上运行窗口功能以进行分页。

使用ORM可以达到这个结果吗?

0 个答案:

没有答案