I have a case like this, where you have a custom nested serializer relation with a unique field. Sample case:
class GenreSerializer(serializers.ModelSerializer):
class Meta:
fields = ('name',) #This field is unique
model = Genre
class BookSerializer(serializers.ModelSerializer):
genre = GenreSerializer()
class Meta:
model = Book
fields = ('name', 'genre')
def create(self, validated_data):
genre = validated_data.pop('genre')
genre = Genre.objects.get(**genre)
return Book.objects.create(genre=genre, **validated_data)
The problem: When i try to save a json object like {"name":"The Prince", "genre": {"name": "History"}} DRF try to validate the genre object unique constraint and if "History" exists throw me an exception because a genre with name "History" must be unique, and that's true but i just trying to relate the object and not create together.
Thank you a lot!!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…