Django Rest Framework: How to Handle Nested Serializer Validation with Dynamic Fields?
I'm working through a tutorial and I'm stuck on something that should probably be simple. I'm working on a Django Rest Framework project where I need to validate nested serializers dynamically based on the input data. I have a parent model `Author` with a related model `Book`. The `BookSerializer` includes a nested `AuthorSerializer`, but I want to conditionally validate the fields of the `AuthorSerializer` based on whether the author already exists in the database or if it's a new instance. Here's how my serializers look: ```python from rest_framework import serializers from .models import Author, Book class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ['id', 'name', 'email'] class BookSerializer(serializers.ModelSerializer): author = AuthorSerializer() class Meta: model = Book fields = ['id', 'title', 'author'] def validate_author(self, value): if 'id' in value: # Check if the author exists if not Author.objects.filter(id=value['id']).exists(): raise serializers.ValidationError('Author does not exist.') else: # Here would be the validation for the case of a new author if not value.get('email'): raise serializers.ValidationError('Email is required for new authors.') return value ``` When I run this code, I receive the following behavior when trying to create a new `Book` with an author that doesn't exist: ``` TypeError: 'NoneType' object is not subscriptable ``` This happens when I attempt to access `value['id']` in the `validate_author` method. I suspect itβs due to how the nested serializer processes the input data. I've tried adding checks to see if `value` is `None` but that hasnβt solved the scenario. How can I properly handle this scenario where the author might or might not be provided in a valid format? I'm currently using Django 3.2 and Django Rest Framework 3.12. How would you solve this? I'm working on a API that needs to handle this. Has anyone else encountered this? This is part of a larger CLI tool I'm building. Any pointers in the right direction?