0023_add_price.py 文件源码

python
阅读 21 收藏 0 点赞 0 评论 0

项目:micromasters 作者: mitodl 项目源码 文件源码
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()
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号