feat: Add sort order to cohorts endpoint#38149
feat: Add sort order to cohorts endpoint#38149brianjbuck-wgu wants to merge 1 commit intoopenedx:masterfrom
Conversation
|
Thanks for the pull request, @brianjbuck-wgu! This repository is currently maintained by Once you've gone through the following steps feel free to tag them in a comment and let them know that your changes are ready for engineering review. 🔘 Get product approvalIf you haven't already, check this list to see if your contribution needs to go through the product review process.
🔘 Provide contextTo help your reviewers and other members of the community understand the purpose and larger context of your changes, feel free to add as much of the following information to the PR description as you can:
🔘 Get a green buildIf one or more checks are failing, continue working on your changes until this is no longer the case and your build turns green. 🔘 Update the status of your PRYour PR is currently marked as a draft. After completing the steps above, update its status by clicking "Ready for Review", or removing "WIP" from the title, as appropriate. Where can I find more information?If you'd like to get more details on all aspects of the review process for open source pull requests (OSPRs), check out the following resources: When can I expect my changes to be merged?Our goal is to get community contributions seen and reviewed as efficiently as possible. However, the amount of time that it takes to review and merge a PR can vary significantly based on factors such as:
💡 As a result it may take up to several weeks or months to complete a review and merge your PR. |
There was a problem hiding this comment.
Pull request overview
This PR adds deterministic alphabetical sorting to the cohorts list endpoint (GET /api/cohorts/v1/courses/{course_id}/cohorts/) by default, and introduces an ordering=asc|desc query parameter to control sort direction.
Changes:
- Adds
orderingquery param handling inCohortHandler.GET, returning HTTP 400 for invalid values. - Extends
cohorts.get_course_cohorts()with anorderingargument and appliesORDER BY name. - Adds API tests covering default ascending order, descending order, and invalid ordering behavior.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| openedx/core/djangoapps/course_groups/views.py | Parses/validates ordering query param and passes it to cohort retrieval. |
| openedx/core/djangoapps/course_groups/cohorts.py | Adds ordering parameter and orders cohort queryset by name. |
| openedx/core/djangoapps/course_groups/tests/test_api_views.py | Adds tests validating ordering behavior and invalid input handling. |
Comments suppressed due to low confidence (1)
openedx/core/djangoapps/course_groups/cohorts.py:337
get_course_cohortsaccepts bothcourseandcourse_id, but the docstring’s Arguments section doesn’t mentioncourse_id. Please documentcourse_id(and clarify the XOR requirement) to keep the signature and docs consistent.
def get_course_cohorts(course=None, course_id=None, assignment_type=None, ordering='asc'):
"""
Get a list of all the cohorts in the given course. This will include auto cohorts,
regardless of whether or not the auto cohorts include any users.
Arguments:
course: the course for which cohorts should be returned
assignment_type: cohort assignment type
ordering: sort direction for results by name ('asc' or 'desc'), defaults to 'asc'
Returns:
A list of CourseUserGroup objects. Empty if there are no cohorts. Does
not check whether the course is cohorted.
"""
assert bool(course) ^ bool(course_id), "course or course_id required"
# Migrate cohort settings for this course
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
You can also share your feedback on Copilot code review. Take the survey.
| def get(self, request, course_key_string, cohort_id=None): | ||
| """ | ||
| Endpoint to get either one or all cohorts. | ||
| """ | ||
| course_key, course = _get_course_with_access(request, course_key_string, 'load') | ||
| if not cohort_id: | ||
| all_cohorts = cohorts.get_course_cohorts(course) | ||
| ordering = request.query_params.get('ordering', 'asc').lower() | ||
| if ordering not in ('asc', 'desc'): |
There was a problem hiding this comment.
The CohortHandler GET endpoint now supports an ordering query param, but the docstring/example requests above this method don’t document it. Please update the endpoint documentation to mention ?ordering=asc|desc and the default behavior so API consumers can discover it via generated docs.
| query_set = query_set.filter(cohort__assignment_type=assignment_type) if assignment_type else query_set | ||
| sort_field = 'name' | ||
| if ordering == 'desc': | ||
| sort_field = '-name' | ||
| query_set = query_set.order_by(sort_field) |
There was a problem hiding this comment.
The docstring says ordering must be 'asc' or 'desc', but the implementation silently treats any other value as ascending. To avoid surprising callers, either validate/normalize ordering in get_course_cohorts (e.g., raise ValueError for invalid values) or adjust the docstring to reflect the fallback behavior.
| self.client.login(username=self.staff_user.username, password=self.password) | ||
| response = self.client.get(path=path, data={'ordering': 'invalid'}) | ||
|
|
||
| assert response.status_code == 400 |
There was a problem hiding this comment.
test_get_cohorts_invalid_ordering only asserts the 400 status. Since this change introduces a specific error payload (developer_message/error_code), it would be more robust to assert at least the error_code (e.g., invalid-ordering-value) so the test doesn’t pass for an unrelated 400 response.
| assert response.status_code == 400 | |
| assert response.status_code == 400 | |
| data = response.json() | |
| assert data.get('error_code') == 'invalid-ordering-value' |
Description
Adds alphabetical ordering to the
GET /api/cohorts/v1/courses/{course_id}/cohorts/endpoint. Previously, the response order was non-deterministic (database insertion order). Cohorts are now returned in ascending alphabetical order by name by default, with an optionalorderingquery parameter to control sort direction.Changes:
get_course_cohorts()now accepts anorderingparameter ('asc'or'desc', default'asc') and appliesORDER BY nameto the queryset. All callers benefit from deterministic ordering.CohortHandler.GETreads the?ordering=asc|descquery parameter, validates it, and passes it through. Returns HTTP 400 for invalid values.User roles impacted: Developers and Operators consuming the cohorts API. No UI changes.
Supporting information
Testing instructions
GET /api/cohorts/v1/courses/{course_id}/cohorts/— verify cohorts are returned A→Z.GET /api/cohorts/v1/courses/{course_id}/cohorts/?ordering=desc— verify cohorts are returned Z→A.GET /api/cohorts/v1/courses/{course_id}/cohorts/?ordering=invalid— verify HTTP 400 is returned.Deadline
None
Other information
orderingparam will now receive cohorts in ascending alphabetical order, which is an improvement over the previous non-deterministic ordering. No response schema changes.