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
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With