何时以及如何使用Django REST Framework验证数据

时间:2016-09-02 11:27:50

标签: django validation django-rest-framework

我有一个模型,它使用Django REST Framework作为资源公开。 我需要在相关端点上执行POST请求时手动创建对象,这就是我使用generics.ListCreateAPIView并覆盖create()方法的原因。

但是我需要检查POST请求的有效负载中给出的参数是否格式正确/现有/等...

我应该在哪里执行此验证,它与串行器有什么关系?

我尝试在相关的Serializer中编写一个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 ??

1 个答案:

答案 0 :(得分:5)

这里是您覆盖的创建方法的实现,取自mixins.CreateModelMixin类:

def create(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    self.perform_create(serializer)
    headers = self.get_success_headers(serializer.data)
    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

如您所见,它获取序列化程序,验证数据并从序列化程序验证的数据执行对象的创建。

如果您需要手动控制对象的创建,perform_create是您需要覆盖的钩子,而不是create

def perform_create(self, serializer):
    # At this, the data is validated, you can do what you want
    # by accessing serializer.validated_data