Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

185
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda