1
我有一个使用Django REST框架作为资源公开的模型。 我需要在相关端点上执行POST请求时手动创建对象,这就是为什么我使用generics.ListCreateAPIView
并覆盖create()
方法。何时以及如何使用Django REST框架验证数据
不过,我需要检查在POST请求的有效负载中给出的参数都能很好地形成/现有/ etc ...
我应该在哪里执行此验证,以及如何将其与串行相关?
我试图在相关的串行器中编写validate()方法,但它永远不会被POST请求调用。
class ProductOrderList(generics.ListCreateAPIView):
model = ProductOrder
serializer_class = ProductOrderSerializer
queryset = ProductOrder.objects.all()
def create(self, request, *args, **kwargs):
data = request.data
# Some code here to prepare the manual creation of a 'ProductOrder' from the data
# I would like the validation happens here (or even before)
po = ProductOrder.objects.create(...)
class ProductOrderSerializer(serializers.ModelSerializer):
class Meta:
model = ProductOrder
def validate(self, data): # Never called
# Is it the good place to write the validator ??
谢谢塞巴斯蒂安,它的作品就像一个魅力! – matt