0

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?

3
  • 3
    You use first, so there is ONE item, nothing to iterate on, what did you expect ? Commented Dec 30, 2021 at 10:20
  • 1
    What about Users.query.filter(email=email).all() ? Commented Dec 30, 2021 at 10:20
  • ohh yes, silly mistake. Thanks for the help @azro Commented Dec 30, 2021 at 10:31

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

2
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)

1 Comment

Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, can you edit your answer to include an explanation of what you're doing and why you believe it is the best approach?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.