count the number of rows with a condition with SQLAlchemy

空扰寡人 提交于 2020-02-25 08:07:06

问题


I have a sqlite table like this. Which has 3 columns. I want to count the number of rows where user_id = 1 is this possible with SQLAlchemy?

class UserImage(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
        photo = db.Column(db.String(250))

This will return all the rows. How to modify this to get my expected result. rows = db.session.query(func.count(UserImage.user_id)).scalar()

Thank you so much in advance.


回答1:


You can do it like this:

UserImage.query.filter(UserImage.user_id == 1).count()

or

db.session.query(UserImage).filter(UserImage.user_id == 1).count()


来源:https://stackoverflow.com/questions/25605410/count-the-number-of-rows-with-a-condition-with-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!