将url参数传递给serializ

2024-09-30 23:30:03 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我的url是,POST/api/v1/my-app/my-model/?myVariable=foo

如何将myVariable传递给序列化程序?在

# serializer.py
class MySerializer(serializers.ModelSerializer):
    class Meta:
        fields = '__all__'
        model = MyModel

    def custom_validator(self):
        # how can i get the "myVariable" value here?
        pass

    def validate(self, attrs):
        attrs = super().validate(attrs)
        self.custom_validator()
        return attrs


# views.py
class MyViewset(ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MySerializer

Tags: pyselfmodelmydefcustomallvalidate
1条回答
网友
1楼 · 发布于 2024-09-30 23:30:03

您可以通过^{}属性访问变量

如何通过序列化程序实现?在

ModelViewSet类将request对象和view对象作为序列化程序上下文数据传递给序列化程序,并且可以在context变量的序列化程序中访问它

方法1:直接使用序列化程序

中的request对象
# serializer.py
class MySerializer(serializers.ModelSerializer):
    class Meta:
        fields = '__all__'
        model = MyModel

    def custom_validator(self):
        request_object = self.context['request']
        myVariable = request_object.query_params.get('myVariable')
        if myVariable is not None:
            # use "myVariable" here
            pass

    def validate(self, attrs):
        attrs = super().validate(attrs)
        self.custom_validator()
        return attrs


方法2:重写get_serializer_context()方法

^{pr2}$

相关问题 更多 >