0

How can I find out that incoming request is a array or not? For now I'm doing this approach

def create(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data)
    if isinstance(request.data, list):
        serializer = self.get_serializer(many=True, data=request.data)

What could be the best way?

1 Answer 1

3

One way to simplify this could this approach:

def create(self, request, *args, **kwargs):
    is_many = isinstance(request.data, list)
    serializer = self.get_serializer(many=is_many, data=request.data)

In this example, I'm assuming that by not passing many in the first function call, it defaults to False.

Since you will always run the test isinstance, might as well call it first and use that as the value for the many parameter.

This way you only ever call the self.get_serializer once.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I did this serializer = self.get_serializer(many=isinstance(request.data, list), data=request.data)

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.