Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think you need to join before you filter and use just one query:</p> <pre><code># Get all the versions of a single course. versions = Curriculum_Version.query.join(Curriculum_Version.course).filter( Course.course_code == "PIP-001").all() </code></pre> <p>Otherwise sqlalchemy will not know to use the relationship before filtering.</p> <p>If you just specify a filter then sqlalchemy does not know to perform a join and you end up with sql similar to this:</p> <pre><code>SELECT curriculum_versions.* FROM curriculum_versions, courses WHERE courses.course_code = "PIP-001" </code></pre> <p>Which does not make a whole lot of sense but is valid SQL. When you use a join it leverages the filter against the correct table like this:</p> <pre><code>SELECT curriculum_versions.* FROM curriculum_versions JOIN courses ON curriculum_versions.course_id = courses.id WHERE courses.course_code = "PIP-001" </code></pre> <p>Note that sqlalchemy knows to use the condition <code>curriculum_versions.course_id = courses.id</code> because you pass in <code>Curriculum_Version.course</code> to <code>query.join()</code> and you specified that relationship on your <code>Curriculum_Version</code> class as the course property and it automatically knows to use the only foreign key available between the <code>curriculum_versions</code> and <code>courses</code> tables (which you also had to specify on the <code>curriculum_versions.course_id</code> column).</p> <p>You can read more about joins here: <a href="http://docs.sqlalchemy.org/en/rel_0_7/orm/tutorial.html#querying-with-joins" rel="nofollow">http://docs.sqlalchemy.org/en/rel_0_7/orm/tutorial.html#querying-with-joins</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload