将此sql转换为flask-sqlalchemy语法

时间:2013-07-11 09:21:24

标签: python mysql sqlalchemy flask flask-sqlalchemy

我正在使用Flask-sqlalchemy 这是mysql:

select u.id, count(i.id) as count from rss_urls as u left join rss_items as i on u.id = i.rss_urls_id group by u.id;

我应该如何将其翻译成sqlalchemy?

非常感谢。

class RSS_urls(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    link = db.Column(db.String(200), unique=True)
    add_time = db.Column(db.DateTime)
    rss_items = db.relationship("RSS_items", backref="base_url", lazy="dynamic")


class RSS_items(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    rss_urls_id = db.Column(db.Integer, db.ForeignKey("RSS_urls.id"))
    link = db.Column(db.String(200))
    title = db.Column(db.String(200))

这是模型。

1 个答案:

答案 0 :(得分:6)

假设您有一个模型RssUrlRssItem,其关系为RssUrl.rss_items

db.session.query(RssUrl.id, db.func.count(RssUrl.id).label("count")
    ).join(RssUrl.rss_items).group_by(RssUrl.id)