如何向序列化模型添加更多参数,以便在使用`to_presentation`时能够使用。

huangapple go评论65阅读模式
英文:

How to add more param to Serialization Model for using at to_presentation

问题

这是我的代码

class DataFieldSerializer(serializers.ModelSerializer):

    class Meta:
        model = DataField
        fields = ["field", "topic", "category", "group", "alias", "units"]

    def __init__(self, *args, **kwargs):
        self.extra_param = kwargs.pop('extra_param', None)
        super().__init__(*args, **kwargs)

    def to_representation(self, instance):
        data = super().to_representation(instance)
        print("Extra Param:", self.extra_param)

这是我如何调用DataFieldSerializer

result_data = DataFieldWithUnitsSerializer(data_fields, many=True, extra_param='example').data

当我运行代码时,我得到了这个结果

Extra Param: None

我猜这不是向模型序列化器添加更多参数的正确方式。

总之,我想找到一种方法来将额外的参数传递给序列化器模型。

英文:

Here is my so

class DataFieldSerializer(serializers.ModelSerializer):

    class Meta:
        model = DataField
        fields = ["field", "topic", "category", "group", "alias", "units"]

    def __init__(self, *args, **kwargs):
        self.extra_param = kwargs.pop('extra_param', None)
        super().__init__(*args, **kwargs)

    def to_representation(self, instance):
        data = super().to_representation(instance)
        print("Extra Param:", self.extra_param)

This is how I call the DataFieldSerializer

result_data = DataFieldWithUnitsSerializer(data_fields, many=True, extra_param='example').data

When I run the code I got this result

Extra Param:None

I guess it is not the right way to add more param into a model serializer.

To sum up, I want to find away to pass an extra param to the Serializer Model

答案1

得分: 1

我认为最好的方法是通过 context 发送,就像这样:

# 序列化器
class DataFieldSerializer(serializers.ModelSerializer):

    class Meta:
        model = DataField
        fields = ["field", "topic", "category", "group", "alias", "units"]

    def to_representation(self, instance):
        data = super().to_representation(instance)
        print("额外参数:", self.context.get('extra_param'))

# 使用
result_data = DataFieldWithUnitsSerializer(data_fields, many=True, context={'extra_param': 'example'}).data
英文:

I think the best way is to send by context, like this:

#serializer
class DataFieldSerializer(serializers.ModelSerializer):

    class Meta:
        model = DataField
        fields = ["field", "topic", "category", "group", "alias", "units"]

    def to_representation(self, instance):
        data = super().to_representation(instance)
        print("Extra Param:", self.context.get('extra_param'))

# usage
result_data = DataFieldWithUnitsSerializer(data_fields, many=True, context= {'extra_param': 'example'}).data

huangapple
  • 本文由 发表于 2023年5月25日 14:07:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76329365.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定