Django Rest Framework: How to properly handle nested serializers with unique validation?
I'm dealing with I'm migrating some code and I've hit a wall trying to I've looked through the documentation and I'm still confused about I'm relatively new to this, so bear with me. I'm working on a Django Rest Framework application where I need to create an API endpoint for a model that includes a nested relationship. The main model `Author` has a one-to-many relationship with `Book`. I want to ensure that when creating or updating an `Author`, the nested `Book` objects are also validated for uniqueness based on the `title`. However, I keep getting a validation error stating that the `title` must be unique, regardless of whether it's a new or existing author. Here's a simplified version of my models: ```python class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, related_name='books', on_delete=models.CASCADE) ``` The serializer I'm using looks like this: ```python from rest_framework import serializers class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ['title'] class AuthorSerializer(serializers.ModelSerializer): books = BookSerializer(many=True) class Meta: model = Author fields = ['name', 'books'] def validate_books(self, books): titles = [book['title'] for book in books] if len(titles) != len(set(titles)): raise serializers.ValidationError('Books must have unique titles.') return books ``` The issue arises when I try to create an `Author` with the following data: ```json { "name": "John Doe", "books": [ {"title": "Book A"}, {"title": "Book A"} ] } ``` I receive an error saying, "{'books': [ErrorDetail(string='Book with this title already exists.', code='unique')]}", which suggests that the validation kicks in before my custom validation function. I've also tried overriding the `create` method in the `AuthorSerializer`, but it doesn't seem to resolve the issue. What am I missing here? How can I ensure that the nested books are validated correctly without triggering the unique constraint error on existing instances? I'm using Django 3.2 and Django Rest Framework 3.12. For context: I'm using Python on macOS. For reference, this is a production application. I'd really appreciate any guidance on this. I recently upgraded to Python 3.10. I'm working with Python in a Docker container on Ubuntu 22.04. This issue appeared after updating to Python LTS. I'd be grateful for any help.