我可以先使用Django annotations
创建额外的列,然后使用Case
和When
根据某些条件确定其值。
例如:
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()
)
否则,我必须为每一列写Case
和when
,这是很多重复的代码。