[英]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
属性访问该变量
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
变量中访问它
request
object in serializerrequest
对象# 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()
methodget_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.