ninjacode
ninjacode

Reputation: 328

db object not iterable in flask

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?

Upvotes: 0

Views: 634

Answers (2)

MH Aiub Alli
MH Aiub Alli

Reputation: 46

email = "[email protected]"
data = []
data = Users.query.filter(email=email).first()
if data:

    # ages = data['age'] # You can use this also 
    age = data.get('age') # Try This 
    # age = data.age #If you don't want to convert into a list
    if age == 15:
         print (age)

Upvotes: 2

CG Zhang
CG Zhang

Reputation: 314

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

Upvotes: 2

Related Questions