Django Rest Framework - ValidationError When Using Nested Serializers with ForeignKey
I tried several approaches but none seem to work. I'm converting an old project and Quick question that's been bugging me - Hey everyone, I'm running into an issue that's driving me crazy. I'm facing a `ValidationError` when trying to create a new `Order` object that has a nested `Product` serializer in Django Rest Framework (DRF). I'm using DRF version 3.12 and Django version 3.2. My models are set up with a `ForeignKey` relationship, and I'm trying to pass a list of product IDs when creating an order. Here's the relevant part of my code: ```python # models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) class Order(models.Model): products = models.ManyToManyField(Product) total_price = models.DecimalField(max_digits=10, decimal_places=2) ``` ```python # serializers.py from rest_framework import serializers from .models import Order, Product class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['id', 'name', 'price'] class OrderSerializer(serializers.ModelSerializer): products = ProductSerializer(many=True) class Meta: model = Order fields = ['id', 'products', 'total_price'] def create(self, validated_data): products_data = validated_data.pop('products') order = Order.objects.create(**validated_data) for product_data in products_data: product = Product.objects.get(id=product_data['id']) order.products.add(product) return order ``` When I send a POST request with the following JSON payload: ```json { "products": [ {"id": 1}, {"id": 2} ], "total_price": 50.00 } ``` I get the following error message: ``` ValidationError: [{'products': [ErrorDetail(string='This field is required.', code='required')]}] ``` I've tried to adjust the serializer to accept raw product IDs instead of the nested objects, but it leads to another error regarding the `ManyToManyField`. I've also checked that the products with IDs 1 and 2 exist in the database. Can anyone help me understand why I'm receiving this `ValidationError`, and how I can modify my serializers to correctly handle a list of product IDs during the order creation process? For context: I'm using Python on Linux. What's the best practice here? For context: I'm using Python on Linux. I'd really appreciate any guidance on this. Is there a better approach? The stack includes Python and several other technologies. What's the correct way to implement this? Any help would be greatly appreciated!