Django:使用Case并分别用于注释创建的多个新列

时间:2018-08-26 12:39:42

标签: django

我可以先使用Django annotations创建额外的列,然后使用CaseWhen根据某些条件确定其值。

例如:

    SomeModel.objects.all()
    .annotate( extra_column_A=Value('False',output_field=CharField()) , extra_column_B=Value('False',output_field=CharField()),....,extra_column_XYZ=Value('False',output_field=CharField()))
    .Case(
        When(
            Some_existing_column < 10,
            then
                extra_colum_A = somevalue1 * Some_existing_column
                extra_column_B = somevalue2 * Some_existing_column
                ...
                ..
                .
                extra_column_XYZ = somevalue3 * Some_existing_column
        ),
        When(
            Some_existing_column < 20,
            then
                extra_colum_A = somevalue * Some_existing_column
                extra_column_B = somevalue * Some_existing_column
                ...
                ..
                .
                extra_column_XYZ = somevalue * Some_existing_column
        ),
        ...
        When(
            Some_existing_column < 200,
            then
                extra_colum_A = somevalue * Some_existing_column
                extra_column_B = somevalue * Some_existing_column
                ...
                ..
                .
                extra_column_XYZ = somevalue * Some_existing_column
        ),
        default = False,
        output_field=IntegerField()
        )

否则,我必须为每一列写Casewhen,这是很多重复的代码。

0 个答案:

没有答案