将url参数传递给序列化器

时间:2019-03-04 12:25:33

标签: python django django-rest-framework

假设我的网址是 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

1 个答案:

答案 0 :(得分:2)

您可以通过request.query_params属性访问该变量

如何通过序列化器实现?

ModelViewSet 类将request对象和view对象作为 serializer上下文数据传递给序列化程序,并且可以访问在 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()方法

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

    def custom_validator(self):
        myVariable = self.context['myVariable']
        #use "myVariable" here

    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

    def get_serializer_context(self):
        context = super().get_serializer_context()
        context.update(
            {
                "myVariable": self.request.query_params.get('myVariable')
            }
        )
        return context