Home > database >  db object not iterable in flask
db object not iterable in flask

Time:01-02

I'm searching for a record in Users db and then looping through all the records. The code is something like below.

email = "[email protected]"
data = Users.query.filter(email=email).first() 
for item in data:
    if item["age"] == 15:
        #do something

The above code throws error Users object not iterable. How can I loop through the records?

CodePudding user response:

Because you only returned one row of data, it cannot be iterable. If your data is not null, you can use ‘data.age’ instead of ‘item["age"]’

email = "[email protected]"
data = Users.query.filter(email=email).first() 
if data.age == 15:
   #do something

CodePudding user response:

email = "[email protected]"
data = Users.query.filter(email=email).all() 

# age = data['age'] # You can use this also 


age = data.get('age') # Try This also
if age == 15:
    pass
  • Related