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?