3

I have a model which is exposed as a resource with Django REST Framework. I need to manually create the objects when a POST requests is performed on the related endpoints, that why I use a generics.ListCreateAPIView and override the create() method.

However I need to check that the parameters given in the payload of the POST request are well-formed/existing/etc...

Where shall I perform this validation, and how is it related with the Serializer?

I tried to write a validate() method in the related Serializer, but it is never called on POST requests.

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 Answer 1

10

Here's the implementation of the create method that you overrided, taken from the mixins.CreateModelMixin class:

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)

As you can see, it gets the serializer, validates the data and performs the creation of the object from the serializer validated data.

If you need to manually control the creation of the object, perform_create is the hook that you need to override, not create.

def perform_create(self, serializer):
    # At this, the data is validated, you can do what you want
    # by accessing serializer.validated_data
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.