简体   繁体   中英

pass url parameter to serializer

Suppose my url be, POST : /api/v1/my-app/my-model/?myVariable=foo

How can I pass the myVariable to the serializer?

# 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

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

Method-1: Use directly the request object in serializer

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

    

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


Method-2: Override the get_serializer_context() method

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

    

    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

    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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