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)
CodePudding user response:
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
CodePudding user response:
hi guys 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)