def copy_prices(apps, schema_editor):
"""
Validate CoursePrice then iterate over CoursePrice and populate Program.price
"""
Program = apps.get_model('courses', 'Program')
CourseRun = apps.get_model('courses', 'CourseRun')
program_prices = {}
# Note: we are not filtering on live here because all Programs will require prices and liveness won't matter
# Validate that there is only one price per program and each run had a price. Else, fail the migration
for run in CourseRun.objects.all():
program = run.course.program
# There must be one and only one price per course run
try:
price = run.courseprice_set.get(is_valid=True).price
except ObjectDoesNotExist as ex:
raise Exception("Migration failed due to a price missing for run {}".format(
run.edx_course_key
)) from ex
if program.id not in program_prices:
program_prices[program.id] = price
elif program_prices[program.id] != price:
raise Exception("One run in program {program} had price {price1} but another had price {price2}".format(
program=program,
price1=program_prices[program.id],
price2=price,
))
# Verify that all programs have prices at this point (might be false if a Program doesn't have any runs)
for program in Program.objects.all():
if program.id not in program_prices:
raise Exception("Program {} does not have a price (probably due to not having any runs)".format(program))
# Now, copy the prices
for program_id, price in program_prices.items():
program = Program.objects.get(id=program_id)
program.price = price
program.save()
评论列表
文章目录