假设我的url是,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
您可以通过^{} 属性访问变量
如何通过序列化程序实现?在
ModelViewSet
类将request
对象和view
对象作为序列化程序上下文数据传递给序列化程序,并且可以在context
变量的序列化程序中访问它方法1:直接使用序列化程序
中的request
对象方法2:重写
^{pr2}$get_serializer_context()
方法相关问题 更多 >
编程相关推荐