-1

hi guys I am trying to convert my query into object but I am getting this error " 'User' object is not iterable"

Below are my codes.

@app.route('/users')
def users():
 
    rows = db.session.query(User).first(); 
    for row in rows:
        data.append(list(row))# data.append([x for x in row])  
    return jsonify(data)
shoaib30
  • 877
  • 11
  • 24

2 Answers2

0

The code you have for querying

rows = db.session.query(User).first(); 

selects the first object found and returns it, else returns None as per docs

if there are multiple rows you are trying to query, use the .all() function as per docs

data = []
rows = db.session.query(User).all(); 
for row in rows:
    data.append(row)
return jsonify(data)

this will fetch all the users and add it to the list

shoaib30
  • 877
  • 11
  • 24
  • shoaib30 Im now getting this error "TypeError: Object of type User is not JSON serializable" – Kelvin Jones Oct 05 '21 at 11:05
  • @KelvinJones that would be outside the scope of this question, look into serializing objects in python [Flask jsonify a list of objects](https://stackoverflow.com/questions/21411497/flask-jsonify-a-list-of-objects) – shoaib30 Oct 05 '21 at 11:10
0

I was able to do this buy using flask mashmallow

ma = Marshmallow(app)

    enter code here

class User(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(200),nullable=False)
    email = db.Column(db.String(200),nullable=False)
    password = db.Column(db.String(200),nullable=False)
  


class UserSchema(ma.Schema):
    class Meta:
        # Fields to expose
        fields = ("email", "password","name")
     # Smart hyperlinking
   
user_schema = UserSchema()
users_schema = UserSchema(many=True)





@app.route("/users/")
def users():
    #row= db.session.query(User)
    all_users = User.query.all()
    results = users_schema.dump(all_users)
    return jsonify(results)





  @app.route("/users/<id>")
    def user_detail(id):
        user = User.query.get(id)
        results = user_schema.dump(user)
        return jsonify(results)
Dharman
  • 30,962
  • 25
  • 85
  • 135