Skip to content

feat: Add sort order to cohorts endpoint#38149

Draft
brianjbuck-wgu wants to merge 1 commit intoopenedx:masterfrom
WGU-Open-edX:feature/38119-cohorts-sort-order
Draft

feat: Add sort order to cohorts endpoint#38149
brianjbuck-wgu wants to merge 1 commit intoopenedx:masterfrom
WGU-Open-edX:feature/38119-cohorts-sort-order

Conversation

@brianjbuck-wgu
Copy link
Contributor

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 optional ordering query parameter to control sort direction.

Changes:

  • get_course_cohorts() now accepts an ordering parameter ('asc' or 'desc', default 'asc') and applies ORDER BY name to the queryset. All callers benefit from deterministic ordering.
  • CohortHandler.GET reads the ?ordering=asc|desc query 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

  1. Create a course with several cohorts whose names are out of alphabetical order.
  2. GET /api/cohorts/v1/courses/{course_id}/cohorts/ — verify cohorts are returned A→Z.
  3. GET /api/cohorts/v1/courses/{course_id}/cohorts/?ordering=desc — verify cohorts are returned Z→A.
  4. GET /api/cohorts/v1/courses/{course_id}/cohorts/?ordering=invalid — verify HTTP 400 is returned.

Deadline

None

Other information

  • No database migrations required.
  • This is a non-breaking change. Existing callers without the ordering param will now receive cohorts in ascending alphabetical order, which is an improvement over the previous non-deterministic ordering. No response schema changes.
  • A v2 endpoint was considered but deemed unnecessary since this is purely an ordering improvement with no schema changes.

@openedx-webhooks openedx-webhooks added the open-source-contribution PR author is not from Axim or 2U label Mar 10, 2026
@openedx-webhooks
Copy link

Thanks for the pull request, @brianjbuck-wgu!

This repository is currently maintained by @openedx/wg-maintenance-openedx-platform.

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 approval

If you haven't already, check this list to see if your contribution needs to go through the product review process.

  • If it does, you'll need to submit a product proposal for your contribution, and have it reviewed by the Product Working Group.
    • This process (including the steps you'll need to take) is documented here.
  • If it doesn't, simply proceed with the next step.
🔘 Provide context

To 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:

  • Dependencies

    This PR must be merged before / after / at the same time as ...

  • Blockers

    This PR is waiting for OEP-1234 to be accepted.

  • Timeline information

    This PR must be merged by XX date because ...

  • Partner information

    This is for a course on edx.org.

  • Supporting documentation
  • Relevant Open edX discussion forum threads
🔘 Get a green build

If 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 PR

Your 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:

  • The size and impact of the changes that it introduces
  • The need for product review
  • Maintenance status of the parent repository

💡 As a result it may take up to several weeks or months to complete a review and merge your PR.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ordering query param handling in CohortHandler.GET, returning HTTP 400 for invalid values.
  • Extends cohorts.get_course_cohorts() with an ordering argument and applies ORDER 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_cohorts accepts both course and course_id, but the docstring’s Arguments section doesn’t mention course_id. Please document course_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.

Comment on lines 572 to +579
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'):
Copy link

Copilot AI Mar 10, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment on lines 346 to +350
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)
Copy link

Copilot AI Mar 10, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
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
Copy link

Copilot AI Mar 10, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
assert response.status_code == 400
assert response.status_code == 400
data = response.json()
assert data.get('error_code') == 'invalid-ordering-value'

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

open-source-contribution PR author is not from Axim or 2U

Projects

Status: Needs Triage

Development

Successfully merging this pull request may close these issues.

3 participants