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