Home > database >  How do I iterate a SQLAlchemy query result using a for loop?
How do I iterate a SQLAlchemy query result using a for loop?

Time:10-01

I use SQLAlchemy as my ORM. Here is my code:

v = db.session.query(A).all()
random = choice(v)
for name in random:
    print(name)

This is the error that I get:

TypeError: 'Cafe' object is not iterable

I need to use a for loop to get all query items, how do I do that?

CodePudding user response:

just remove

random = choice(v)

CodePudding user response:

v = db.session.query(A).all()

returns a ORM-level SQL construction object which holds the data from your query which are the columns of your tables.

If your table does contain a column named name you first have to access that and then select a random value.

query_results = db.session.query(A).all()

# create an empty list to add 'names' to
names = []

# iterate over the data found in query_results
for result in query_results:
    # append the value of the 'name' column for the current table index
    names.append(result.name)

# choose a random value from the names list
random_name = random.choice(names)

CodePudding user response:

This code works

row_as_dict = {column: str(getattr(row, column)) for column in row.__table__.c.keys()}
  • Related