|
| 1 | +""" |
| 2 | +Properly assign course cohorts to learners. |
| 3 | +""" |
| 4 | + |
| 5 | +import logging |
| 6 | + |
| 7 | +from django.core.management import BaseCommand, CommandError |
| 8 | + |
| 9 | +from opaque_keys import InvalidKeyError |
| 10 | +from opaque_keys.edx.keys import CourseKey |
| 11 | + |
| 12 | +from openedx.core.djangoapps.course_groups.cohorts import get_course_cohorts, add_user_to_cohort |
| 13 | + |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +class Command(BaseCommand): |
| 19 | + """ |
| 20 | + Populate learners in cohorts for a course. |
| 21 | + """ |
| 22 | + help = 'Populate learners in cohorts for a course' |
| 23 | + |
| 24 | + def add_arguments(self, parser): |
| 25 | + """ |
| 26 | + Add arguments to the command parser. |
| 27 | + """ |
| 28 | + parser.add_argument( |
| 29 | + '--course', |
| 30 | + action='store', |
| 31 | + type=str, |
| 32 | + required=True, |
| 33 | + help='Comma separated course IDs of the courses whose learners need to be linked to cohorts.' |
| 34 | + ) |
| 35 | + |
| 36 | + def handle(self, *args, **options): |
| 37 | + course_ids = options['course'].split(',') |
| 38 | + for course_id in course_ids: |
| 39 | + try: |
| 40 | + course_key = CourseKey.from_string(course_id) |
| 41 | + except InvalidKeyError: |
| 42 | + raise CommandError('Course ID %s is incorrect' % course_id) |
| 43 | + |
| 44 | + course_cohorts = get_course_cohorts(course_id=course_key) |
| 45 | + logger.info('%s cohorts found for %s', course_cohorts.count(), course_id) |
| 46 | + for cohort in course_cohorts: |
| 47 | + logger.info('%s users found for cohort %s', cohort.users.all().count(), cohort.name) |
| 48 | + for user in cohort.users.all(): |
| 49 | + logger.info('Adding %s to cohort %s', user.email, cohort.name) |
| 50 | + try: |
| 51 | + __, previous_cohort, __ = add_user_to_cohort(cohort, user) |
| 52 | + if previous_cohort: |
| 53 | + logger.info('%s previously belonged to %s', user.email, previous_cohort) |
| 54 | + except ValueError: |
| 55 | + logger.warning('User %s already present in the cohort %s', user.email, cohort.name) |
0 commit comments