[Django]-Accessing join query results in SQLAlchemy

8👍

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)

0👍

You can execute your query differently:

for row in query.all():
    print row[1].name, row[1].gender

Leave a comment