简体   繁体   English

将 url 参数传递给序列化程序

[英]pass url parameter to serializer

Suppose my url be, POST : /api/v1/my-app/my-model/?myVariable=foo假设我的网址是, POST/api/v1/my-app/my-model/?myVariable=foo

How can I pass the myVariable to the serializer?如何将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

You can access the variable via request.query_params attribute您可以通过request.query_params属性访问该变量

How it's possible through serializer ?如何通过序列化程序实现?

The ModelViewSet class passing the request object and view object to the serializer as serializer context data , and it's accessible in serializer in context variable ModelViewSet类将request对象和view对象作为序列化器上下文数据传递给序列化器,并且可以在序列化器中的context变量中访问它

Method-1: Use directly the request object in serializer方法一:直接使用序列化器中的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


Method-2: Override the get_serializer_context() method方法 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM