如何避免多个循环来获得sqlalchemy查询中所需的排序?

2024-04-26 00:02:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习pyramid和sqlalchemy,并且正在努力学习如何在没有嵌套的foreach循环的情况下最好地在数据库中执行查询。我相信有一个更有效的方法。你知道吗

我有以下型号:

    class User(Base):
        __tablename__ = 'users'
        id = Column(Integer, primary_key=True)
        username = Column(Text)
        topicsfollowing = relationship('Topic', secondary=users_topics,
                                       backref='followers')

    class Article(Base):
        __tablename__ = 'articles'
        id = Column(Integer, primary_key=True)
        name = Column(Text)
        body = Column(Text)
        datepublished = Column(DateTime)
        focusid = Column(Integer, ForeignKey("topics.id"))
        focus = relationship("Topic", backref=backref('articles', order_by=id))

    class Topic(Base):
        __tablename__ = 'topics'
        id = Column(Integer, primary_key=True)
        name = Column(Text)

我还设置了用户和主题之间的M2M关系,如下所示:

    users_topics = Table('users_topics', Base.metadata,
                  Column('userid', Integer, ForeignKey('users.id')),
                  Column('topicid', Integer, ForeignKey('topics.id')))

从本质上说,我的用户可以关注主题,并且有关于每个主题(焦点)的文章。我想找出的是一种有效的方法,从用户关注的所有主题集合中获取10篇最新文章的列表。例如,一个特定的主题可以提供所有10个最近的主题,或者可能有10个主题,每个主题提供一篇最近的文章。你知道吗

我唯一能想到的办法是:

    user = DBSession.query(User).filter_by(id=logged_in).first()
    for topic in user.topicsfollowing:
        for article in topic.articles:
            # from here assemble a list of all articles from all followed
            # topics and then sort them descending by datepublished and take 
            # the first 10 in the list

但我知道必须有一个更有效的方法。任何帮助都将不胜感激。你知道吗


Tags: 方法keytextinid主题basecolumn
1条回答
网友
1楼 · 发布于 2024-04-26 00:02:41

只需执行一个查询,即可获得用户正在跟踪的主题ID列表,然后执行以下操作:

query(Article).filter(Article.focusid.in_(topic_ids)).order_by(desc(Article.datepublished)).limit(10)

我把它写在脑子里,所以我不确定它是否100%正确,但是请看docs中的“IN”操作符。你知道吗

相关问题 更多 >