英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论