Reputation: 173
I'm running a Flask app with flask_SQLAlchemy and Postgres DB.
I want to print() all columns values for a row retrieved with query.all()
I've read over this document, but I was not able to retrieve what I'm looking for. https://docs.sqlalchemy.org/en/13/orm/query.html I'm new to Alchemy though.
# the class model
class Users(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, nullable=False)
hash = db.Column(db.String, nullable=False)
reg_date = db.Column(db.DateTime, nullable=False)
enabled = db.Column(db.Boolean, nullable=False
# Query all users
users = Users.query.all()
# try to iterate
for row in users:
print(row.all())
actual results:
before loop:
>>> <Users 1>, <Users 2>, <Users 3>, <Users 4>
after loop:
>>> error all() doesn't apply to row
expected result, not achieved:
>>>
{id="1", username="yyy", hash="xxx", reg_date"zzz", enabled"yyy"}
....
{id="n", username="ttt", hash="nnn", reg_date"jjjj", enabled"oooo"}
Upvotes: 4
Views: 28688
Reputation: 5071
all
is used once in order to fetch all the records, then you should use the column names for display or anything else you'd like to do:
users = Users.query.all()
for user in users:
print(user.username)
print(user.reg_date)
print(f"<id={user.id}, username={user.username}>")
In order to achieve your desired result, which is to print the list of all users, you can print the users
variable:
print(users)
You should note that the users
list contains Users
objects, so printing the list will actually dump their representation - and if you want to control how these objects are displayed, you can use the __repr__
method inside your Users
model (object):
def __repr__(self):
return f"<id={self.id}, username={self.username}>"
Upvotes: 8