Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
how to make custom serializer which can handle nested post data for Create API endpoint?

Due to unique business needs, I have to customize the Create API endpoint. Default behavior in django-rest-framework is like this.

class Customer(models.Model):
    fieldA = models.IntegerField(null=True, blank=True)
    fieldB = models.CharField(max_length=5, blank=True)
    ... ...

class CustomerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Customer
        fields = '__all__'

class CustomerListCreateAPIView(generics.ListCreateAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerSerializer

post data

{
    fieldA: 1,
    fieldB: 'some string'
}

it sends respond with Created status

{
    id: 1,
    fieldA: 1,
    fieldB: 'some string'
}

However, I want to post data with nested data and validate

{
    "customer": {
        "fieldA": 1,
        "fieldB": "some string"
    }
}

Expected response data should be

{
    "customer": {
        "id": 1,
        "fieldA": 1,
        "fieldB": "some string"
    }
}

Also validation should show nested error messages

{
    "customer": "customer field is required"
}

{
    "customer": {
        "fieldA": ["filedA is required"],
    }
}

How can I archieve this?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can create an ApiView and validate each single data by iterating. If all the data is valid then create the objects.

Example:



class CustomerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Customer
        fields = '__all__'

class CustomerListCreateAPIView(APIView):
    def post(self, request, *args, **kwargs):
        customers = request.data.get('customer', None)
        for customer in customers:
            validated_data = CustomerSerializer(data=customer)
            # if invalid Raise Validation error 
        objects = []
        for customer in customers:
            validated_data = CustomerSerializer(data=customer)
            customer = Customer.objects.create(validated_data)
            objects.append(customer.id)

        return Response(
            CustomerSerializer(Customer.objects.filter(id__in=objects), many=True).data)
    
over 4 years ago · Santiago Trujillo Report

0

Here is my revised approach. It creates new instance using serializer and sends nested validation error messages.

class CustomerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Customer
        fields = '__all__'


class CustomerView(generics.ListCreateAPIView):
    queryset = Customer.objects.all()

    def create(self, request, *args, **kwargs):
        customer = request.data.get('customer', None)
        if not customer:
            raise serializers.ValidationError({'customer': 'customer field is required'})

        serializer = CustomerSerializer(data=customer)
        serializer.is_valid(raise_exception=False)
        if serializer.errors:
            error = {
                'customer': serializer.errors
            }
            return Response(error, status=status.HTTP_400_BAD_REQUEST)

        data = serializer.save()
        headers = self.get_success_headers(serializer.data)
        return Response(data, status=status.HTTP_201_CREATED, headers=headers)

Validation errors:

{
    "customer": "customer field is required"
}

{
    "customer": {
        "fieldA": ["filedA is required"],
    }
}

Hope this will help others.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!