Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 413
John Peter Avatar asked Mar 04 '19 12:03

John Peter


1 Answers

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 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

# 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
like image 112
JPG Avatar answered Oct 11 '22 05:10

JPG