def METHOD_NAME(apps, schema_editor):
    """
    Set the order for existing enrollments.
    """
    CourseRunEnrollment = apps.get_model("courses", "CourseRunEnrollment")
    ProgramEnrollment = apps.get_model("courses", "ProgramEnrollment")
    Order = apps.get_model("ecommerce", "Order")
    Product = apps.get_model("ecommerce", "Product")
    def get_order(user, product):
        """Return the order for a user and product if any"""
        return (
            Order.objects.filter(lines__product_version__product=product)
            .filter(purchaser=user)
            .order_by("id")
            .first()
        )
    run_enrollments = (
        CourseRunEnrollment.objects.filter(order=None).order_by("id").iterator()
    )
    for enrollment in run_enrollments:
        order = None
        try:
            product = Product.objects.get(
                content_type__model="courserun", object_id=enrollment.run.id
            )
            order = get_order(enrollment.user, product)
        except Product.DoesNotExist:
            log.debug("Product does not exist for courserun %d", enrollment.run.id)
        if not order and enrollment.run.course.program:
            # No matching course run order found, must be part of a program
            try:
                product = Product.objects.get(
                    content_type__model="program",
                    object_id=enrollment.run.course.program.id,
                )
                order = get_order(enrollment.user, product)
            except Product.DoesNotExist:
                log.debug(
                    "Product does not exist for program %d",
                    enrollment.run.course.program.id,
                )
                continue
        if not order:
            log.error("No matching order found for CourseEnrollment %d", enrollment.id)
        else:
            enrollment.order = order
            enrollment.save()
    program_enrollments = (
        ProgramEnrollment.objects.filter(order=None).order_by("id").iterator()
    )
    for enrollment in program_enrollments:
        try:
            product = Product.objects.get(
                content_type__model="program", object_id=enrollment.program.id
            )
            order = get_order(enrollment.user, product)
        except Product.DoesNotExist:
            log.exception(
                "Product does not exist for program %d", enrollment.program.id
            )
            continue
        if not order:
            log.error("No matching order found for ProgramEnrollment %d", enrollment.id)
        else:
            enrollment.order = order
            enrollment.save()