2016-07-06 54 views
0

目前,我有以下查詢:明確指定 「FROM」 表

query = self.session.query(Student, School).join(
    Person.student, aliased=True).join(
    Student.school, aliased=True).filter(
    Person.id == 1) 

來編譯這個SQL。

SELECT student.id AS student_id, student.school_id AS student_school_id, student.person_id AS student_person_id, school.id AS school_id, school.name AS school_name 
FROM student, school, person JOIN student AS student_1 ON person.id = student_1.person_id JOIN school AS school_1 ON school_1.id = student_1.school_id 
WHERE person.id = :id_1 

我希望查詢保持完全,因爲它是,但我想從語句從Person模型是專。因此,像

SELECT * FROM person JOIN ... WHERE person.id = :id_1 

我覺得aliased kwarg是搞亂了的狀態。 kwarg刪除了aliased修復了這種行爲,但我需要別名kwarg作爲特殊用例。如何從「FROM」語句中刪除studentschool表。

回答

2

aliased參數.join使用匿名走樣,這意味着StudentSchool您傳遞給session.query是表的不同的「實例」。

from sqlalchemy.orm import aliased 

aliased_student = aliased(Student) 
aliased_school = aliased(School) 

query = (
    session.query(aliased_student, aliased_school) 
    .select_from(Person) 
    .join(aliased_student, Person.student) 
    .join(aliased_school, Student.school) 
    .filter(Person.id == 1)) 

在這裏你可以看到,你可以告訴.join哪個別名加入到關係時使用。