Django Serializer Not Validating Nested Object Correctly - AttributeError on Save
After trying multiple solutions online, I still can't figure this out. I'm working with Django REST framework (version 3.12.4) and I've encountered an scenario with serializing and validating nested objects. I have a `Book` model that includes a foreign key to an `Author` model. When I try to validate the serializer for creating a new book along with the author information, I'm getting an `AttributeError: 'NoneType' object has no attribute 'id'` when I attempt to save the book instance. Here's my current setup: ```python # models.py class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, on_delete=models.CASCADE) ``` ```python # serializers.py from rest_framework import serializers class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ['id', 'name'] class BookSerializer(serializers.ModelSerializer): author = AuthorSerializer() class Meta: model = Book fields = ['id', 'title', 'author'] def create(self, validated_data): author_data = validated_data.pop('author') author = Author.objects.create(**author_data) return Book.objects.create(author=author, **validated_data) ``` When I try to create a new book with the following request: ```json { "title": "Sample Book", "author": { "name": "John Doe" } } ``` I am currently using the following view: ```python # views.py from rest_framework import generics from .models import Book from .serializers import BookSerializer class BookCreateView(generics.CreateAPIView): queryset = Book.objects.all() serializer_class = BookSerializer ``` I expected it to create both the book and the author, but instead, I receive the aforementioned behavior when saving the book. I've verified that the `author` data is being passed correctly to the serializer and that `author_data` is not empty. What am I missing here? Any insights would be greatly appreciated! I'm working on a CLI tool that needs to handle this. How would you solve this?