I'm having an issue with an SQLalchemy query. When i query a specific table it returns 7 items but when I iterate over it, it only finds one item.
Here is the query;
seasons = db.session.query(Seasons).filter(Seasons.tmdb_id == tmdb_id)
I know it returns 7 items because I immediately type the following and it prints the numeber "7";
print(seasons.count())
However when I try to iterate over this seasons object like this expecting to get 7 names, I only get one row with one name.
for item in seasons:
print(item.name)
Here is my Seasons class in my models.py
# Main TV show table
class Seasons(db.Model):
__tablename__ = 'tv_seasons'
tmdb_id = db.Column(db.Integer, primary_key=True)
season_id = db.Column(db.Integer)
air_date = db.Column(db.String)
name = db.Column(db.String)
episode_count = db.Column(db.Integer)
overview = db.Column(db.String)
poster_path = db.Column(db.String)
season_number = db.Column(db.Integer)
Any idea why this is happening?
Because the count()
function returns a int value. Take a look: https://docs.sqlalchemy.org/en/14/orm/query.html#sqlalchemy.orm.Query.count
SELECT count(1) AS count_1 FROM (
SELECT <rest of query follows...>
) AS anon_1
The above SQL returns a single row, which is the aggregate value of the count function; the Query.count() method then returns that single integer value.
So, you should to use Query(...).all()
to iterate on items.
then use if
to check if has data:
seasons = query(...).all()
if seasons:
for item in seasons:
print(item.name)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.