Skip to content

Commit

Permalink
Use a subquery instead of a join for the assignment user filter
Browse files Browse the repository at this point in the history
In general a subquery is better for filtering, in this case because:

- It allows us to compose a query better, we don't have to worry about
  missing/duplicating a join

- It can be faster for non-correlated subqueries (ie queries that
  produce the same values for all rows). This should be the case here.

- They don't introduce duplicate rows, we can remove the distinct here.
  • Loading branch information
marcospri committed Aug 21, 2024
1 parent 4188890 commit b4e0de3
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions lms/services/assignment.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,16 +275,18 @@ def get_assignments( # noqa: PLR0913
)

if h_userids:
query = (
query.join(AssignmentMembership)
.join(User)
.where(User.h_userid.in_(h_userids))
query = query.where(
Assignment.id.in_(
select(AssignmentMembership.assignment_id)
.join(User)
.where(User.h_userid.in_(h_userids))
)
)

if course_ids:
query = query.where(Assignment.course_id.in_(course_ids))

return query.order_by(Assignment.title, Assignment.id).distinct()
return query.order_by(Assignment.title, Assignment.id)

def get_courses_assignments_count(self, **kwargs) -> dict[int, int]:
"""Get the number of assignments a given list of courses has."""
Expand Down

0 comments on commit b4e0de3

Please sign in to comment.