问题
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