'Writable nested serializer method getting an Error while posting a request

models.py

class Client(models.Model):


    client_id = models.AutoField(unique=True, primary_key=True)
    org = models.ForeignKey(Organisation, on_delete=models.CASCADE, related_name='org',null=True)
    product = models.ManyToManyField(Product,related_name='product')
    client_name = models.CharField(max_length=100)
    client_code = models.CharField(max_length=20)
    client_logo = models.ImageField(upload_to=upload_to,storage=DownloadableS3Boto3Storage, null=True, blank=True)
    currency = MoneyField(max_digits=10, decimal_places=2, default_currency='INR', null=True)
    billing_method = models.CharField(max_length=40)
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)
    email_id = models.EmailField(max_length=100)
    contact_no = models.CharField(max_length=20)
    mobile_no = models.CharField(max_length=20)
    description = models.TextField(max_length=500)
    street_address = models.CharField(max_length=250)
    city = models.CharField(max_length=50)
    state = models.CharField(max_length=50)
    country = models.CharField(max_length=50)
    pincode = models.CharField(max_length=10)
    industry = models.CharField(max_length=100)
    company_size = models.IntegerField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    is_active = models.IntegerField(default=0, choices=STATUS_CHOICES)


    class Meta:
        db_table = "client_master"

    def __str__(self):
        return self.client_name

serializers.py

class Client_Serializers(serializers.ModelSerializer):
    #product_name = Product_Serializers(many=True)
    product = Product_Serializers(many=True)
    class Meta:
        model = Client
        fields = ('client_id','currency','billing_method','first_name','last_name','description','street_address','city','state','country','pincode','industry','company_size','client_name', 'contact_no','mobile_no', 'email_id','client_logo','client_code','product',)

    def create(self, validated_data):
        products_data = validated_data.pop('product')
        product = Product.objects.create(**validated_data)
        for product_data in products_data:
            Product.objects.create(product=product, **product_data)
        return product

Data receiving on GET method

{
            "client_id": 3,
            "currency": "0.05",
            "billing_method": "credit card",
            "first_name": "career",
            "last_name": "lab",
            "description": "NA",
            "street_address": "tiliconveli",
            "city": "tirunelveli",
            "state": "tamilnadu",
            "country": "India",
            "pincode": "600200",
            "industry": "software",
            "company_size": 100,
            "client_name": "techfetch",
            "contact_no": "1234567890",
            "mobile_no": "1234567890",
            "email_id": "[email protected]",
            "client_logo": "https://icanio-project-management.s3.amazonaws.com/client_logo/sup_bat_fDauRxK.jpg",
            "client_code": "TFH",
            "product": [
                {
                    "product_id": 5,
                    "product_name": "time"
                }
            ]
        }

But while posting it in the same format it is not getting posted, showing like

{
    "status": "error",
    "code": 400,
    "data": {
        "product": [
            "This field is required."
        ]
    },
    "message": "success"
}

Views.py for reference

class Client_Viewset(DestroyWithPayloadMixin,viewsets.ModelViewSet):
    renderer_classes = (CustomRenderer, )
    queryset=models.Client.objects.all()
    serializer_class=serializers.Client_Serializers
    parser_classes = [MultiPartParser, FormParser]



    filter_fields = (
        'client_id',
        'client_name',
        'client_code',
        'org_id',
    )

How can I post the same data which I get in the GET request of Product field. Please help me resolve this as I was stuck in there for two days. I tried so many ways and end up not getting posted.

Product model

class Product(models.Model):
    product_id = models.AutoField(unique=True, primary_key=True)
    product_name = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "product_master"

    def __str__(self):
        return self.product_name

product serializer

class Product_Serializers(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ('product_id','product_name',)


Solution 1:[1]

From your code, the Client_Serializers is for Client model but the create method is not creating any Client object.

Client_Serializers should be something on these lines -

class Client_Serializers(serializers.ModelSerializer):
    product = Product_Serializers(many=True)
    class Meta:
        model = Client
        fields = ('client_id','currency','billing_method','first_name','last_name','description','street_address','city','state','country','pincode','industry','company_size','client_name', 'contact_no','mobile_no', 'email_id','client_logo','client_code','product',)

    def create(self, validated_data):
        products_data = validated_data.pop('product')
        client = Client.objects.create(**validated_data) # Create a client object
        for product_data in products_data:
            Product.objects.create(client=client, **product_data)
        return client

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 krskara