django序列化程序动态设置属性

时间:2018-08-31 08:57:47

标签: django serializer

是否可以动态设置Serializer的属性?

CONTEXT_CLASSES = dict()
contexts = ['EmailContext', 'SmsMessageContext',...]

for ctx in contexts:
    Ctx_class = getattr(sys.modules[__name__], f'{ctx}Serializer')
    ctx_class_instance = Ctx_class(many=False, required=False, read_only=True)
    attr_name = ctx.split('Context')[0].lower() + '_ctx'
    CONTEXT_CLASSES[attr_name] = ctx_class_instance


class ContextContainerSerializer(serializers.ModelSerializer):

    for attr_name, instance in CONTEXT_CLASSES.items():
        # set attributes somehow

    class Meta:
         ...
         fields = tuple([value[0] for value in CONTEXT_CLASSES.values()])

将其放入__init__中将不起作用,因为class Meta是在其之前执行的,并且设置了已经包含属性名称并会引发django.core.exceptions.ImproperlyConfigured的fields变量。

1 个答案:

答案 0 :(得分:2)

您可以在初始化时设置属性

PartNo  SerialNo    StepNo  CostType    Cost
ABC      123        10      Labor       11
ABC      123        10      Material    16
ABC      456        10      Labor       21
ABC      456        10      Material    26
ABC      789        10      Labor       21
ABC      789        10      Material    16
ABC      1011       10      Labor       11
ABC      1011       10      Material    6
ABC      1112       10      Labor       1
ABC      1112       10      Material    -4
ABC      123        20      Labor       11
ABC      123        20      Material    19
ABC      456        20      Labor       24
ABC      456        20      Material    29
ABC      789        20      Labor       24
ABC      789        20      Material    19
ABC      1011       20      Labor       14
ABC      1011       20      Material    9
ABC      1112       20      Labor       4
ABC      1112       20      Material    -1
ABC      123        30      Labor       11
ABC      123        30      Material    13
ABC      456        30      Labor       18
ABC      456        30      Material    23
ABC      789        30      Labor       18
ABC      789        30      Material    13
ABC      1011       30      Labor       8
ABC      1011       30      Material    3
ABC      1112       30      Labor       -2
ABC      1112       30      Material    -7

要获得更多动态控件/模式,请使用PartNo SerialNo StepNo CostType Cost DEF Aplha 10 Labor 2 DEF Zed 10 Labor 3 DEF Kelly 10 Labor 4 DEF Aplha 20 Labor 3 DEF Zed 20 Labor 2 DEF Kelly 20 Labor 5 DEF Aplha 30 Labor 6 DEF Zed 30 Labor 7 DEF Kelly 30 Labor 5 DEF Aplha 40 Labor 3 DEF Zed 40 Labor 4 DEF Kelly 40 Labor 2 DEF Aplha 50 Labor 8 DEF Zed 50 Labor 9 DEF Kelly 50 Labor 7

class ContextContainerSerializer(serializers.ModelSerializer):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # should be able to access "self.Meta"
        for attr_name, instance in CONTEXT_CLASSES.items():
            setattr(self.Meta, attr_name, instance)