I am trying to create a serializer to create multiple products with one payload. Here's my attempt:
# models.py
class Product(models.Model):
sku = models.CharField(unique=True)
product_name = models.CharField()
# serializers.py
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
def create(self, validated_data):
try:
product = create_product( **validated_data)
except:
raise CustomException( detail = { "error" : "Unable to create product" } )
# views.py
class ProductCreate(generics.CreateAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
def get_serializer(self, *args, **kwargs):
kwargs["many"] = True
return super().get_serializer(*args, **kwargs)
So, this works well when the data are clean. Here's a response:
[ { "id" : 1, "sku" : "12345", "product_name" : "Product A" },
{ "id" : 2, "sku" : "56789", "product_name" : "Product B" }]
But if one of the products fails to be created, the error message is simply:
# response
{ "error" : "Unable to create product" }
What I'd like is the response to be a list, where each element corresponds to the product element in the request. For example, product A is created, but product B returns an error.
[ { "id" : 1, "sku" : "12345", "product_name" : "Product A" },
{ "error" : "Unable to create product" } ]
How can I get this type of response?