count the number of rows with a condition with SQLAlchemy
13,512
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()
Author by
Michelle De Waas Gunawardena
Updated on June 18, 2022Comments
-
Michelle De Waas Gunawardena almost 2 years
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.