假设我的网址是 POST :/api/v1/my-app/my-model/?myVariable=foo
如何将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
答案 0 :(得分:2)
您可以通过request.query_params
属性访问该变量
ModelViewSet
类将request
对象和view
对象作为 serializer上下文数据传递给序列化程序,并且可以访问在 context
变量的序列化器中
request
对象# 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()
方法# 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