Chase Choi Chase Choi - 1 year ago 64
Python Question

Should all key names be specified when tables join on Sqlalchemy

Here are the example tables:


1. students

studentID -- PK

studentName

collegeID


2. colleges

collegeID -- PK

collegeName



I wanted to get all of students key values and all of colleges key values




Here is the example sqlalchemy query.

from example.database import dao
...
...
example = dao.query(students).\
join(colleges,
students.collegeID == colleges.collegeID).\
all()


but It didn't have collegeName data. only had students data.

So I had to change it.

example = dao.query(students.studentID,
students.studentName,
stduents.collegeID,
colleges.collegeName).\
join(colleges, students.collegeID == colleges.collegeID).\
all()


How can I do this easier and faster without specifying all keys I want.

van van
Answer Source
example = (dao.query(students, colleges)
    .join(colleges, students.collegeID == colleges.collegeID)
    ).all()

for student, college in example:
    print(student, college)

This will return a list of tuple values:

 <student-1, college-1>
 <student-1, college-2>
 ...
 <student-N, college-?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download