If I have:
query = db.session.query(Food, Person).filter(Food.id == Person.favourite_food)
for row in db.session.execute(query)
print row
The output for first print I get is:
(1, u'Alice', 25, u'F', u'z', None, False, 1, u'icecream', 1, None, False)
(5, u'Bob', 38, u'M', u'z', None, False, 3, u'pizza', 1, None, False)
How do I do:
print row.name, row.gender # <-- how do I do this?
The result does not seem to have column names anymore.
Edit: And also is there a way to serialise the query results with just one line, something like
return Response(json.dumps(query.results), mimetype='application/json')
When you specify
query(Food, Person)
the resultant rows will be of type sqlalchemy.util._collections.result, and it will have two fields: Food and Person
the Food part can be referenced either by row[0] or row.Food the Person part can be referenced either by row[1] or row.Person
so e.g.
print(row.Person.name, row.Person.gender) # works
print(row[1].name, row[1].gender) # also works
if you only wanted particular fields, you could specify them in the query, eg:
query = (db.session.query(Person.name, Person.gender, Food.name.label('foodname'))
.filter(Food.id == Person.favourite_food))
and then the object will have 3 fields: name, gender, foodname
print(row.name, row.gender, row.foodname)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With